1、先創建 .net core Web 應用程式,選擇API 2、安裝 Nuget 包:Nlog.Web.AspNetCore install-package Nlog install-package Nlog.Web.AspNetCore 或者打開Nuget管理界面搜索Nlog.Web.AspNe ...
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 >Warn> Error> Fatal
<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="taskfile" 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="runfile" 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 = "*" levels="Error,Warn,Critical" writeTo="errorfile" /> <logger name = "*" level="Info" writeTo="taskfile" /> <logger name = "*" level="Warn" writeTo="runfile" final="true"/> </rules> </nlog>nlog.config
參考github: https://github.com/nlog/nlog/wiki