NLog is applicable to a variety of applications. NET platform (including. NET standard), a flexible, free logging platform. NLog makes it easy to write to multiple targets. (database, file, console) and change the logging configuration instantly.

NLog supports both structured and traditional logging.

The focus of NLog is: high performance, easy to use, easy to scale and flexible configuration.

Characteristics of the

Easy to configure

NLog is very easy to configure, both through configuration files and programmatically. You can change the configuration without restarting the application.

Can the templated

Each log message can be templated using various layout renderings

extensible

Even though NLog has targets and predefined layouts, you can write custom targets or pass custom values

Structured log

Full support for structured logging

The target

A target is used to display, store, or pass log messages to another target. NLog can dynamically write one of multiple destinations for each log message.

More than 30 targets are readily available, including:

The document

Write logs to any number of files using automatic file naming and archiving. By default, NLog does not lock your files.

Event logging

Write event logs locally or remotely

The database

Store logs in a.NET supported database

The console

Real-time writing to the command line console, including color coding of messages

E-mail

You can send an E-mail whenever an application error occurs

ASP.NET core Record

Writes the log message to the ASP.NET Core log record

There are also wrapper targets that provide buffering, load balancing, failover situations, asynchronous writes, and more. A complete list of targets is on the configuration options page. If you can’t find a target that fits your needs, you can easily write a custom target.

support

NLog supports the following platforms:

  • .NET Framework 3.5, 4, 4.5-4.8

  • .NET Framework 4 client configuration file

  • Xamarin Android

  • Xamarin iOs

  • Windows Phone 8

  • Silverlight 4 and 5

  • Mono 4

  • ASP.NET 4 (nlog.web package)

  • ASP.NET Core (nlog.web.aspNetcore package)

  • .NET Core (nlog.extensions.logging package)

  • The.net Standard 1. X-ray NLog 4.5

  • The.net Standard 2. X-ray NLog 4.5

  • UWP NLog – 4.5

    An introduction to

Create a new ASP.NET Core project

In Visual Studio 2019.

Add dependencies to CSPROj manually or using NuGet

Install the latest version:

  • NLog. Web. AspNetCore 4.9 +

  • Update the NLog package if possible

In the csproj:

<PackageReference Include=" nlog.web.aspnetcore "Version="4.9.0" /> <PackageReference Include="NLog" Version="4.6.7" />Copy the code

Create an nlog.config file.

Create the nlog.config (all lowercase) file in the root directory of the project.

Let’s use the following example:

<? The 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" autoReload="true" internalLogLevel="Info" internalLogFile="c:\temp\internal-nlog.txt"> <! -- 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>Copy the code

Enable copying to the bin folder

Enable copying to the bin folder for nlog.config

Or. Csproj manually edit the file and add:

To update the program. The cs

To update the program. The cs

using System;
using NLog.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;

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();
    }
}

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
Copy the code

Configuration appsettings. Json

The logging configuration specified in appSettings. json overrides any calls to SetMinimumLevel. So “Default”:, please delete it or adjust it correctly according to your needs.

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
Copy the code

Write the log

Inject ILogger into your controller:

using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; _logger.LogDebug(1, "NLog injected into HomeController"); } public IActionResult Index() { _logger.LogInformation("Hello, this is the index!" ); return View(); }Copy the code

Sample output

When we start the ASP.NET Core site, we get two files:

nlog-own-2019-10-14.log
2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main |url: |action: |ASP.NET_Core_3___VS2019.Program.Main
2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController |url: https://localhost/|action: Index|ASP.NET_Core_3___VS2019.Controllers.HomeController..ctor
2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! |url: htt

nlog-all-2019-10-14.log
2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main 
2019-10-14 23:15:10.9142|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using 'C:\Users\Julian\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. 
2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 
2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 
2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Content root path: D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019 
2019-10-14 23:15:11.3238|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/   
2019-10-14 23:15:11.3434|0|INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executing endpoint 'ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019)' 
2019-10-14 23:15:11.3867|3|INFO|Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker|Route matched with {action = "Index", controller = "Home"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller ASP.NET_Core_3___VS2019.Controllers.HomeController (ASP.NET Core 3 - VS2019). 
2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController 
2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! 
2019-10-14 23:15:11.4161|1|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executing ViewResult, running view Index. 
2019-10-14 23:15:11.5831|4|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executed ViewResult - view Index executed in 167.626ms. 
2019-10-14 23:15:11.5831|2|INFO|Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker|Executed action ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019) in 196.6052ms 
2019-10-14 23:15:11.5831|1|INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executed endpoint 'ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019)' 
2019-10-14 23:15:11.5910|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 267.9366ms 200 text/html; charset=utf-8 
2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/jquery/dist/jquery.min.js   
2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/css/site.css   
2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/bootstrap/dist/css/bootstrap.min.css   
2019-10-14 23:15:11.6365|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/bootstrap/dist/js/bootstrap.bundle.min.js   
2019-10-14 23:15:11.6365|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/js/site.js?v=4q1jwFhaPaZgr8WAUSrux6hAuh0XDg9kPS3xIVq36I0   
2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/js/site.js'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\js\site.js' 
2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/css/site.css'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\css\site.css' 
2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 28.7787ms 200 application/javascript 
2019-10-14 23:15:11.6696|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 52.4825ms 200 text/css 
2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.bundle.min.js'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\lib\bootstrap\dist\js\bootstrap.bundle.min.js' 
2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.min.css'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\lib\bootstrap\dist\css\bootstrap.min.css' 
2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/jquery/dist/jquery.min.js'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\lib\jquery\dist\jquery.min.js' 
2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 50.937400000000004ms 200 application/javascript 
2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 70.65100000000001ms 200 text/css 
2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 71.51610000000001ms 200 application/javascript
Copy the code