NLog已經是日誌庫的一員大佬,使用也簡單方便,本文介紹的環境是居於.NET CORE 3.0 css
Install-Package NLog.Web.AspNetCore
在web項目根目錄下,建立配置文件nlog.config ,而且將文件的屬性「複製到輸出目錄」設置爲"始終複製"。git
<?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="f:\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="f:/temp/dwlogs/${level}/${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="f:/temp/dwlogs/${level}/${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>
using System; using System.Collections.Generic; using System.Text; namespace Dw.Util { /// <summary> /// 日誌記錄 /// </summary> public class NLogHelp { /// <summary> /// 輸出操做日誌到NLog /// </summary> public static void WriteInfo(string msg) { //寫入操做日誌 const string mainLogger = "logger"; var logger = NLog.LogManager.GetLogger(mainLogger); logger.Info(msg); } /// <summary> /// 輸出錯誤日誌到NLog /// </summary> public static void WriteError(string msg) { //寫入操做日誌 const string mainLogger = "logger"; var logger = NLog.LogManager.GetLogger(mainLogger); logger.Error(msg); } /// <summary> /// 輸出異常日誌到NLog /// </summary> public static void WriteDebug(string msg) { //寫入操做日誌 const string mainLogger = "logger"; var logger = NLog.LogManager.GetLogger(mainLogger); logger.Debug(msg); } } }
NLogHelp.WriteInfo("用戶開始訪問。。。"); NLogHelp.WriteError("這裏產生了錯誤。。。"); NLogHelp.WriteDebug("這裏產生了BUG。。。");
參考文檔:https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3github