Asp.Net Core自帶內建日誌,同時也容許開發人員輕鬆切換到其餘日誌框架。下面將在實戰項目中使用NLog記錄日誌。git
1.首先建立Asp.Net Core Web項目github
2.在項目中添加NLog相應包web
Install-Package NLog.Web.AspNetCore -Version 4.8.0
3.在項目中添加NLog配置文件數據庫
Install-Package NLog.Config
NLog.config添加至項目中後,在VS中右擊文件,查看屬性,並將文件屬性設置爲始終複製或者更新時複製網絡
4.編輯NLog.config文件mvc
雙擊文件,進入編輯,根據須要修改內容。app
配置文件主要包括兩個部分:輸出目標target和路由規則rule。框架
4.1輸出目標targetui
每一個target表明一個輸出目標,它主要包含兩個屬性:name和type。name是輸出模板的名稱,在後面的路由規則中使用,type則是輸出類型,常見的有url
當選擇某一種類型的時候,還須要配置相應的參數。如輸出類型是File時,咱們要配置日誌路徑filename,這裏是可使用一些變量的(花括號裏面的部分),舉例:
fileName="${basedir}/Logs/Error/${shortdate}/error.txt"
輸出的日誌格式爲 /Log/2014-10-01/err.txt 天天生成一個文件夾,很是方便。
輸出格式的控制:
有的時候,咱們須要對時間、異常等這些對象的輸出格式進行控制。它們能夠經過修改layout參數來實現。這一部分是相對比較複雜的,具體配置參數請到官網查看。
4.2路由規則rule
路由規則主要用於將日誌和輸出目標匹配起來,它通常有以下幾個屬性
看上去有好幾個屬性,實際上用起來仍是比較簡單的,好比:
<logger name="*" writeTo="console" /> 將全部的日誌輸出到控制檯中
<logger name="*" minlevel="Debug" writeTo="debugger" /> 將Debug級別以上的日誌輸出到Debugger中
<logger name="*" minlevel="Error" writeTo="error_file" /> 將Error級別以上的日誌輸出到文件中
另外,NLOG支持配置多個路由規則,能夠很是方便咱們的輸出。
具體詳情請看官網參數說明:https://github.com/nlog/NLog/wiki/Configuration-file#configuration-file-locations
下面是個人配置文件:
<?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" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log"> <!-- optional, add some variables https://github.com/nlog/NLog/wiki/Configuration-file#variables --> <variable name="myvar" value="myvalue"/> <!-- See https://github.com/nlog/nlog/wiki/Configuration-file for information on customizing logging rules and outputs. --> <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}" /> <!-- add your targets here See https://github.com/nlog/NLog/wiki/Targets for possible targets. See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers. --> <!-- Write events to a file with the date in the filename. <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" /> --> </targets> <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" /> <!-- Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f" <logger name="*" minlevel="Debug" writeTo="f" /> --> </rules> </nlog>
5.在startup.cs中注入日誌
public Startup(IConfiguration configuration, IHostingEnvironment env) { env.ConfigureNLog("NLog.config"); Configuration = configuration; } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //... //add NLog to ASP.NET Core loggerFactory.AddNLog(); //... }
運行項目後,產生日誌記錄
6.全局異常處理
添加過濾器;並在Startup.cs文件的ConfigureServices方法中添加過濾器
public class GlobalExceptionFilter: IExceptionFilter { public static Logger logger = LogManager.GetCurrentClassLogger(); public void OnException(ExceptionContext filterContext) { logger.Error(filterContext.Exception); var result = new BaseResult() { ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode,//系統異常代碼 ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg,//系統異常信息 }; filterContext.Result = new ObjectResult(result); filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; filterContext.ExceptionHandled = true; } }