ASP.NET Core 2.0 使用NLog实现日志记录

1、安装NuGet包

1、Install-Package NLog.Web.AspNetCore

2、Install-Package NLog

在csproj中编辑:

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

Github源码示例

2、创建一个nlog.config文件。

<?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>

  <!-- 从记录器名称映射到目标的规则 -->
  <rules>
    <!--所有的记录,包括从微软-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--跳过非关键微软日志,因此只记录自己的日志-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <!-- BlackHole -->
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>
View Code

布局渲染器使用指南

3、在csproj手动编辑文件并添加

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

4、更新program.cs

        public static void Main(string[] args)
        {
            // NLog:首先设置记录器以捕获所有错误
            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
            {
                //确保在退出应用程序之前刷新并停止内部定时器/线程(避免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用于依赖注入 
                .Build();
View Code

5、配置appsettings.json

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

6、写日志

        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、输出示例

 

猜你喜欢

转载自www.cnblogs.com/lwc1st/p/8979942.html