1、先创建 .net core Web 应用程序,选择API
2、安装 Nuget 包:Nlog.Web.AspNetCore
install-package Nlog install-package Nlog.Web.AspNetCore
或者打开Nuget管理界面搜索Nlog.Web.AspNetCore(我安装的版本是V4.9.0)
3、添加配置文件: nlog.config
注意,此处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" 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>nlog.config(来源:官方文档)
配置appsettings.json
"Logging": { "LogLevel": { "Default": "Trace", "Microsoft": "Information" } }
4、注册日志依赖
方法一:通过修改Program.cs
//需引用 //using Microsoft.Extensions.Logging; //using NLog.Web; public class Program { public static void Main(string[] args) { NLog.Web.NLogBuilder.ConfigureNLog("nlog.config"); CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureLogging(logging => { logging.ClearProviders(); //移除已经注册的其他日志处理程序 logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); //设置最小的日志级别 }) .UseNLog(); }Program.cs
方法二:通过修改Startup.cs里的Configure函数
//需引用 //using NLog.Extensions.Logging; //using NLog.Web; public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); loggerFactory.AddNLog();//添加NLog env.ConfigureNLog("nlog.config");//读取Nlog配置文件 app.UseMvc(); }Configure
5、修改 Controller, 输出日志:
[Route("api/")] public class LoginController : Controller { private ILogger<LoginController> logger; public LoginController(ILogger<LoginController> _logger) { logger = _logger; } [Route("Login")] [HttpGet] public stringLogin() { logger.LogInformation("Info日志"); logger.LogError("Error日志"); logger.LogWarning("Warning日志"); logger.LogCritical("Critical日志"); logger.LogWarning("Warning日志"); logger.LogTrace("Trace日志"); logger.Log(LogLevel.Warning, "LogWarn日志"); logger.Log(LogLevel.Debug, "LogDebug日志"); logger.Log(LogLevel.Error, "LogError日志"); return ""; } }控制器
打印日志的时候有两种方式
logger.Log(LogLevel.Warning, "LogWarning日志:"); //标红的地方可以选择日志的级别
logger.LogWarning("Warning日志");//直接调内置的级别函数
6、结果
程序跑起来之后会出现前两个文件~访问完接口后会出现最后那个文件
internal-nlog 记录了NLog的启动及加载config的信息。
nlog-all 记录了所有日志
nlog-own 记录了我们自定义的日志
7、修改配置
打开官方提供的nlog.config 配置参考 https://github.com/NLog/NLog/wiki/Configuration-file
子节点<target> 配置参考 https://nlog-project.org/config/?tab=targets
属性Layout表示输出文本格式 配置参考 https://nlog-project.org/config/?tab=layouts
子节点<rule> 日志的路由表 顺序是从上往下 一个<logger>就是一个路由信息
日志级别:Trace >Debug> Information >Warning> Error> Critical
<logger>属性:
name - 日志源/记录者的名字 (允许使用通配符*) minlevel : 匹配日志范围的最低级别 maxlevel : 匹配日志范围的*别 level : 单一日志级别 levels : 一系列日志级别,由逗号分隔 writeTo : 日志应该被写入的目标,由逗号分隔,与target的你name对应 final : 为true标记当前规则为最后一个规则。其后的logger不会运行
附最后的配置文档
<?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" > <!-- the targets to write to --> <targets> <!-- write logs to file --> <target xsi:type="File" name="allfile" fileName="log\${shortdate}-All.log" layout="${longdate} | ${event-properties:item=EventId_Id:whenEmpty=0} | ${uppercase:${level}}|${logger} |${message} ${exception:format=tostring}" /> <!-- another file log, only own logs.Uses some ASP.NET core renderers --> <target xsi:type="File" name="errorfile" fileName="log\${shortdate}-Error.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}" /> <target xsi:type="File" name="warnfile" fileName="log\${shortdate}-Warn.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}" /> <target xsi:type="File" name="infofile" fileName="log\${shortdate}-Info.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 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.*" level="Error" /> <logger name = "*" level="Error" writeTo="errorfile" /> <logger name = "Microsoft.*" level="Info" /> <logger name = "*" level="Info" writeTo="infofile" /> <logger name = "Microsoft.*" level="Warn" final="true"/> <logger name = "*" level="Warn" writeTo="warnfile" /> </rules> </nlog>nlog.config
参考github: https://github.com/nlog/nlog/wiki