一、NLog 简介
NLog 是一个基于.NET 平台编写的类库,我们可以适应NLog在应用程序中添加极为完善的跟踪代码。
NLog是一个简单灵活的.NET日志记录类库。通过使用NLog,我们可以在任何一种.NET语言中输出带有上下文的(contextual information)调试诊断信息,根据喜好配置其表现样式之后发送到一个或多个输出目标(target)中。
二、NLog安装配置
安装NuGet包:NLog和NLog.Web.AspNetCore
并新增 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" internalLogLevel="Info">
<!-- 启用.net core的核心布局渲染器 -->
<extensions>
<add assembly="NLog.Web.AspNetCore" />
</extensions>
<!-- 写入日志的目标配置 -->
<targets>
<!-- 调试 -->
<target xsi:type="File" name="debug" fileName="logs/debug-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
<!-- 警告 -->
<target xsi:type="File" name="warn" fileName="logs/warn-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
<!-- 错误 -->
<target xsi:type="File" name="error" fileName="logs/error-${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>
<!-- 调试 -->
<logger name="*" minlevel="Trace" maxlevel="Debug" writeTo="debug" />
<!--跳过不重要的微软日志-->
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<!-- 警告 -->
<logger name="*" minlevel="Info" maxlevel="Warn" writeTo="warn" />
<!-- 错误 -->
<logger name="*" minlevel="Error" maxlevel="Fatal" writeTo="error" />
</rules>
</nlog>
在Program.cs类中注入
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NLog.Demo
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseNLog();
}
}
三、NLog基本使用
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogError("错误信息!");
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
日志文件输出地址:bin\Debug\netcoreapp3.1\logs\日志文件