ASP.NET Core 2.0 uses NLog to implement logging

1. Install NuGet package

1、Install-Package NLog.Web.AspNetCore

2、Install-Package NLog

Edit in csproj:

<PackageReference Include="NLog" Version="4.5.3" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.5.3" />

Github source code example

2. Create an nlog.config file.

<?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"
      throwConfigExceptions="true"
      internalLogLevel="info"
      internalLogFile="D:\temp\internal-nlog.txt">
  <!-- 要写的目标-->
  <targets>
    <!--将日志写入文件  -->
    <target xsi:type="File" name="allfile" fileName="D:\temp\nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

    <!-- 启用asp.net核心布局渲染器 -->
    <target xsi:type="File" name="ownFile-web" fileName="D:\temp\nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />
  </targets>

  <!-- Rule mapping from logger name to target --> 
  < rules > 
    <!-- All records, including from Microsoft --> 
    < logger name ="*" minlevel ="Trace" writeTo ="allfile"  />

    <!-- Skip non-critical Microsoft logs, so only log your own --> 
    < logger name ="Microsoft.*" maxlevel ="Info" final ="true"  /> 
    <!-- BlackHole --> 
    < logger name ="*" minlevel ="Trace" writeTo ="ownFile-web"  /> 
  </ rules > 
</ nlog >
View Code

 

Layout Renderer Usage Guidelines

 

 

3、在csprojManually edit the file and add

  <ItemGroup>
    <Content Update="nlog.config" CopyToOutputDirectory="Always" />
  </ItemGroup>

4. Update program.cs

        public static void Main(string[] args)
        {
            // NLog: first set up logger to catch all errors 
            var logger = NLog.Web.NLogBuilder.ConfigureNLog( " nlog.config " ).GetCurrentClassLogger();
             try
            {
                logger.Debug("init main");
                BuildWebHost(args).Run();
            }
            catch (Exception exception)
            {
                // NLog:catch安装错误 
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Make sure to flush and stop internal timers/threads before exiting the application (avoids segmentation faults on Linux) 
                NLog.LogManager.Shutdown();
            }
        }

        public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                })
                .UseNLog()    // NLog: setup NLog is used for dependency injection.Build 
                ();
View Code

5. Configure appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Information"
    }
  }
}
View Code

6. Write a log

        private  readonly ILogger _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();
        }
View Code

7. Output example

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325142750&siteId=291194637