ASP.NET Core 開發-Logging 使用NLog 寫日志文件。
NLog 可以適用於 .NET Core 和 ASP.NET Core 。
ASP.NET Core已經內置了日志支持,可以輕松輸出到控制台。
學習Logging 組件的相關使用,使用NLog 將日志寫入到文件記錄。
Logging 使用
新建一個 ASP.NET Core 項目,為了方便,我選擇Web 應用程序,改身份驗證 改為 不進行身份驗證。
新建好以后,會自動引用好對應的 類庫。這樣我們就可以直接使用 Logger。
Logger 在 Controller的使用
public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation("你訪問了首頁"); _logger.LogWarning("警告信息"); _logger.LogError("錯誤信息"); return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } }
使用DI 直接可以使用對象。
你會發現日志信息輸出來的是亂碼,這里我們要指定輸出格式。
需要添加 System.Text.Encoding.CodePages 引用
Install-Package System.Text.Encoding.CodePages -Pre
然后在 Startup.cs —> Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
這樣在控制台顯示就不會出現亂碼。
日志級別:Trace -》Debug-》 Information -》Warning-》 Error-》 Critical
級別包含范圍由大到小 ,如 Trace 就包含了所有信息。
NLog 使用
NLog 在 ASP.NET Core中的使用。
1.添加引用。
Install-Package NLog.Extensions.Logging -Pre
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" internalLogLevel="Warn" internalLogFile="internal-nlog.txt"> <!-- define various log targets --> <targets> <!-- write logs to file --> <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="nlog-own-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}| ${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> </targets> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip Microsoft logs and so log only own logs--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
3.在 Startup.cs -》 Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddNLog();//添加NLog
運行程序,你就會發現,項目下多了兩個文件,證明成功執行。
這里 nlog-all-*.log 是記錄所有日志,nlog-own-*.log 記錄跳過Microsoft 開頭的類庫輸出的相關信息,剩下的信息。
4.發布(dotnet publish)注意事項
在 project.json 的 publishOptions節點 加入 nlog.config
"publishOptions": { "include": [ "wwwroot", "Views", "appsettings.json", "web.config", "nlog.config"//加上nlog配置文件 ] },
GitHub :https://github.com/linezero/Blog/tree/master/NETCoreLogging
如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。