.Net日志之nlog
生活随笔
收集整理的這篇文章主要介紹了
.Net日志之nlog
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 介紹
NLog是適用于各種.NET平臺(包括.NET標準)的靈活,免費的日志記錄平臺,支持數據庫、文件、控制臺。
2. 輸入到文件
2.1 引用nuget包
????<PackageReference?Include="NLog"?Version="4.7.6"?/><PackageReference?Include="NLog.Web.AspNetCore"?Version="4.9.3"?/>2.2 創建NLog配置文件
在項目目錄中新建一個xml文件的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"><targets?async="true"><target?name="file"?xsi:type="File"layout="${longdate}?${logger}?${message}${exception:format=ToString}"fileName="${basedir}/logs/${date:format=yyyy-MM-dd}.txt"keepFileOpen="true"encoding="utf-8"?/><target?name="console"?xsi:type="Console"><attribute?name="time"?layout="${date:format=yyyy-MM-dd?HH\:mm\:ss.fff?zzz}"?/><attribute?name="category"?layout="${logger}"?/><attribute?name="log_level"?layout="${level:lowerCase=true}"?/><attribute?name="message"?layout="${message}"?/><attribute?name="trace_id"?layout="${aspnet-TraceIdentifier:ignoreActivityId=true}"?/><attribute?name="user_id"?layout="${aspnet-user-identity}"?/><!--取得該條日志生產者名字--><attribute?name="exception"?layout="${exception:format=tostring}"?/></target></targets><rules><logger?name="*"?minlevel="Info"?writeTo="console"???ruleName="console"?/><logger?name="*"?minlevel="Debug"?writeTo="file"?/></rules> </nlog>2.3 Program中修改
using?Microsoft.AspNetCore.Hosting; using?Microsoft.Extensions.Hosting; using?Microsoft.Extensions.Logging; using?NLog.Web; using?System;namespace?NlogDemo {public?static?class?Program{public?static?void?Main(string[]?args){var?logger?=?NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();try{logger.Debug("init?main");CreateHostBuilder(args).Build().Run();}catch?(Exception?ex){//NLog:?catch?setup?errorslogger.Error(ex,?"Stopped?program?because?of?exception");throw;}finally{NLog.LogManager.Shutdown();}}public?static?IHostBuilder?CreateHostBuilder(string[]?args)?=>Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder?=>{webBuilder.UseStartup<Startup>();}).ConfigureLogging((_,?loggerBuilder)?=>{loggerBuilder.ClearProviders();loggerBuilder.SetMinimumLevel(LogLevel.Information);}).UseNLog();} }2.4 配置日志級別
{"Logging":?{"LogLevel":?{"Default":?"Information","Microsoft":?"Warning","Microsoft.Hosting.Lifetime":?"Information"}} }2.5 控制器使用
????????private?readonly?ILogger<HomeController>?_logger;public?HomeController(ILogger<HomeController>?logger){_logger?=?logger;_logger.LogDebug(1,?"NLog?injected?into?HomeController");}[HttpGet]public?string?Get(){_logger.LogTrace("Trace");_logger.LogDebug("debug");_logger.LogInformation("info");_logger.LogWarning("warn");_logger.LogError("error");_logger.LogCritical("Critical");return?default;}查看輸出的日志文件
image.png3. 參考文檔
https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-5
總結
以上是生活随笔為你收集整理的.Net日志之nlog的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 温故知新,.Net Core遇见Blaz
- 下一篇: 你管这叫线程安全?