您好,登錄后才能下訂單哦!
Asp.net core中,自帶的Log是在當selfhost運行時,在控制臺中輸出,不便于查閱,如果用一個log架框,把日志持久化,便于查詢.
NLog是一個免費的日志記錄框架,專門為.net平臺下的框架提供日志功能,本文主要說明asp.net core下怎么使用NLog。
首先用Nuget安裝NLog.Extensions.Logging和NLog.Web.AspNetCore兩個類庫。
修改project.json,在publishOptions中添加”nlog.config節點”
"publishOptions": {
"include": [
"wwwroot",
"**/*.cshtml",
"appsettings.json",
"web.config",
"nlog.config"
]
}
在StartUp.cs中添加
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); //為NLog.web注入HttpContextAccessor services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); …… } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //添加NLog到.net core框架中 loggerFactory.AddNLog(); //添加NLog的中間件 app.AddNLogWeb(); //指定NLog的配置文件 env.ConfigureNLog("nlog.config"); …… }
HomeController.cs中是自定義日志
static Logger Logger = LogManager.GetCurrentClassLogger(); public IActionResult Index() { Logger.Info("普通信息日志"); Logger.Debug("調試日志"); Logger.Error("錯誤日志"); Logger.Fatal("異常日志"); Logger.Warn("警告日志"); Logger.Trace("跟蹤日志"); Logger.Log(NLog.LogLevel.Warn, "Log日志"); try { int i = 0; var a = 10 / i; } catch (Exception exc) { //異常日志 Logger.Fatal(exc, exc.Message); } return View(); }
NLog.config,有兩種日志,記錄在C:\temp下,一種是全部日志,一種是自己通過NLog函數記錄的日志。如果日志庫異常,會產生在c:\temp\internal-nlog.txt下,
<?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="c:\temp\internal-nlog.txt"> <!-- ASP.NET Core 使用 --> <extensions> <add assembly="NLog.Web.AspNetCore"/> </extensions> <targets> <!-- 全部日志文件 --> <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <!-- 自定義記錄的日志文件 --> <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" /> <target xsi:type="Null" name="blackhole" /> </targets> <rules> <!--所括asp.net core下的全部日志--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--僅自定義記錄的日志文件--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
Layout中$后的數據就是要寫日志的內容,關于這些數據可參考https://github.com/nlog/nlog/wiki/Layout-Renderers,可以根據自己的需要,選擇要保存的日志數據,如下圖是web中的日志數據:
如果想把日志保存到數據庫中,可以把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="c:\temp\internal-nlog.txt"> <!-- ASP.NET Core 使用 --> <extensions> <add assembly="NLog.Web.AspNetCore"/> </extensions> <!-- 注意配置連接字符串 --> <targets> <target name="database" xsi:type="Database" connectionString="server=.;database=nglogdb;uid=SQL用戶名;pwd=SQL密碼;"> <commandText> INSERT INTO [dbo].[NLog] ( [MachineName], [SiteName], [Logged], [Level], [UserName], [Message], [Logger], [Properties], [Host], [Controller], [Action], [Url], [CallSite], [Exception] ) VALUES ( @machineName, @siteName, @logged, @level, @userName, @message, @logger, @properties, @host, @controller, @action, @url, @callSite, @exception ); </commandText> <parameter name="@machineName" layout="${machinename}" /> <parameter name="@siteName" layout="${iis-site-name}" /> <parameter name="@logged" layout="${date}" /> <parameter name="@level" layout="${level}" /> <parameter name="@username" layout="${aspnet-user-identity}" /> <parameter name="@message" layout="${message}" /> <parameter name="@logger" layout="${logger}" /> <parameter name="@properties" layout="${all-event-properties:separator=|}" /> <parameter name="@host" layout="${aspnet-request-host}" /> <parameter name="@controller" layout="${aspnet-MVC-Controller}" /> <parameter name="@action" layout="${aspnet-MVC-Action}" /> <parameter name="@url" layout="${aspnet-request-url}" /> <parameter name="@callSite" layout="${callsite}" /> <parameter name="@exception" layout="${exception:tostring}" /> </target> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="database"/> </rules> </nlog>
數據庫數據如下:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。