ASP.NET Core: Logging file using NLog
By FoxLearn 3/8/2020 7:17:57 PM 8.33K
If you want to integrate NLog in ASP.NET Core, you can do as the following step.
Right-clicking on your project, then select Manage Nuget Packages. Next, Search 'NLog', then install 'NLog.Schema', 'NLog.Config', 'NLog.Extensions.Logging', 'NLog.Web.AspNetCore' to your project.
After you finish installing the NLog library, you can find NLog.config in your project.
Right-clicking on NLog.config file, then select Properties => set Copy to Output Directory to Copy if newer
Opening your NLog.config file, then modify your configuration as shown below.
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="true" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log"> <!-- enable asp.net core layout renderers --> <extensions> <add assembly="NLog.Web.AspNetCore"/> </extensions> <!-- the targets to write to --> <targets> <!-- write logs to file --> <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" /> <!-- another file log, only own logs. Uses some ASP.NET core renderers --> <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" /> </targets> <!-- rules to map from logger name to target --> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip non-critical Microsoft logs and so log only own logs--> <logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo --> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
Creating a Temp folder in your C:\ disk, and don't forget to set the permissions to read and write.
Opening your Program class, then modify your Main method as shown below.
public static void Main(string[] args) { var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Debug("init main"); CreateHostBuilder(args).Build().Run(); } catch (Exception exception) { //NLog: catch setup errors logger.Error(exception, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } }
and don't forget to modify the CreateHostBuilder method allows you to use NLog.
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .UseNLog(); // NLog: Setup NLog for Dependency injection
You can also modify your CreateHostBuilder method as shown below.
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddDebug(); logging.AddNLog(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
If you get an error
ILoggingBuilder' does not contain a definition for 'AddNLog' and no extension method 'AddNLog' accepting a first argument of type 'ILoggingBuilder'.
You should add the NLog.Extension.Logging to your Program.cs
using NLog.Extensions.Logging;
Opening HomeController, then modify your Index action as shown below.
public IActionResult Index() { _logger.LogInformation("NLog Info logging..."); return View(); }
Running your project, then you can see log file in the temp directory.
Through this c# example, i hope so you can use NLog with ASP.NET Core. In the next article, I'll show you how to use NLog database in ASP.NET Core.