.Net Core項(xiàng)目如何添加日志功能詳解
一、微軟內(nèi)置的日志組件
在.Net Core中使用模板新建的Web Api項(xiàng)目時(shí),會(huì)自動(dòng)加入日志功能。只需要在控制器中注入ILogger就可以了。命名空間為:Microsoft.Extensions.Logging
。
會(huì)發(fā)現(xiàn)只有Error被打印到了控制臺(tái),Trace沒有被打印。那是因?yàn)樵赼ppsetting.json中配置了Logging>Console>Default的等級(jí)為Debug,日志的等級(jí)大于等于Debug才會(huì)輸出到控制臺(tái)。在這里說(shuō)一下LogLevel:Trace<Debug<Information<Warning<Error<Critical<None
。
當(dāng)打開appsettings.development.json文件你會(huì)發(fā)現(xiàn)跟appsettings.json配置不同。如下:
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } }
例如:
"System": "Information"
表示命名空間以System開頭的類中且日志等級(jí)大于等于Information才會(huì)輸出到控制臺(tái)。
"Default": "Debug"
表示除以System和Microsoft開頭的命名空間日志等級(jí)大約等于Debug才會(huì)輸出到控制臺(tái)。
這里說(shuō)明一下到底是在什么時(shí)候,讀取了appsettings.json中的配置了了? 其實(shí)是在Program中 WebHost.CreateDefaultBuilder(arge)
。
打開源碼發(fā)現(xiàn)
當(dāng)然我們可以不用微軟提供的默認(rèn)配置
public class Program { public static void Main(string[] args) { //指定配置文件路徑 var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile($"appsettings.json", true, true) .AddJsonFile($"appsettings.{EnvironmentName.Development}.json", true, true); var config = configBuilder.Build(); var host = new WebHostBuilder() .UseKestrel() .UseStartup<Startup>() .UseContentRoot(Directory.GetCurrentDirectory()) .UseUrls(config["AppSettings:Url"])//設(shè)置啟動(dòng)時(shí)的地址 .Build(); host.Run(); } }
配置文件為:
{ "AppSettings": { "Url": "http://0.0.0.0:6000" }, "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Info" } }, "Console": { "LogLevel": { "Default": "Warning" } } } }
StartUp為:
public class Startup { public IConfiguration Configuration { get; private set; } public Startup(IHostingEnvironment env)//在構(gòu)造函數(shù)中注入 IHostingEnvironment { Configuration = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile($"appsettings.json") .Build(); } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //添加控制臺(tái)輸出 loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); } }
但是微軟提供的內(nèi)置的日志組件沒有實(shí)現(xiàn)將日志記錄到文件、數(shù)據(jù)庫(kù)上。下面介紹NLog
二、NLog
首先使用NuGet添加NLog,然后在Startup的Configure中添加以下代碼
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //添加控制臺(tái)輸出 loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); loggerFactory.AddNLog();//添加NLog NLog.LogManager.LoadConfiguration($@"{env.ContentRootPath}/nlog.config");//指定NLog的配置文件 app.UseMvc(); }
配置NLog的配置文件
<?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">--> <targets> <target name="allfile" xsi:type="File" fileName="./logs/${shortdate}/all.log" layout="${longdate}|${message} ${exception}" /> <target name="debugfile" xsi:type="File" fileName="./logs/${shortdate}/debug.log" layout="${longdate}|${message} ${exception}" /> <target name="infofile" xsi:type="File" fileName="./logs/${shortdate}/info.log" layout="${longdate}|${message} ${exception}" /> <target name="warnfile" xsi:type="File" fileName="./logs/${shortdate}/warn.log" layout="${longdate}|${message} ${exception}" /> <target name="errorfile" xsi:type="File" fileName="./logs/${shortdate}/error.log" layout="${longdate}|${message} ${exception}" /> <target name="fatalfile" xsi:type="File" fileName="./logs/${shortdate}/fatal.log" layout="${longdate}|${message} ${exception}" /> <target name="network" xsi:type="Network" address="udp://chinacloudapp.cn:4561" layout="Development|${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />//將日志通過(guò)網(wǎng)絡(luò)輸出 <target name="debuge" xsi:type="Console"/>//將日志輸出到控制臺(tái) </targets> <rules> <logger name="*" minlevel="Trace" writeTo="allfile,debuge" /> <logger name="*" level="Info" writeTo="infofile" /> <logger name="*" level="debug" writeTo="debugfile" /> <logger name="*" level="warn" writeTo="warnfile" /> <logger name="*" level="error" writeTo="errorfile" /> <logger name="*" level="fatal" writeTo="fatalfile" /> </rules> </nlog>
xsi:type=“File”
存儲(chǔ)日志為文件格式 ,
xsi:type="Console"
表示為控制臺(tái)輸出。
fileName="./logs/${shortdate}/all.log"
表示存儲(chǔ)文件路徑。
layout="${longdate}|${message} ${exception}"
表示為文件內(nèi)容的布局。
rules標(biāo)簽下面表示,對(duì)應(yīng)等級(jí)的日志寫到對(duì)應(yīng)target中。如
<logger name="*" level="Info" writeTo="infofile" />
表示等級(jí)為Info的日志寫到target名稱為infofile的文件中。
<logger name="*" minlevel="Trace" writeTo="allfile,debuge" />
表示日志等級(jí)大于Trace的日志寫到target名稱為allfile和debuge(控制臺(tái)輸出)中。
同樣在使用的時(shí)候,只需要在用到的地方注入ILogger,就可以使用了。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- .net core日志結(jié)構(gòu)化
- .net core 使用阿里云分布式日志的配置方法
- ASP.NET Core擴(kuò)展庫(kù)之Http日志的使用詳解
- ASP.NET Core擴(kuò)展庫(kù)之日志功能的使用詳解
- .NET Core3.0 日志 logging的實(shí)現(xiàn)
- .NET Core下使用Log4Net記錄日志的方法步驟
- Asp.Net Core用NLog記錄日志操作方法
- .NET Core開發(fā)日志之OData(Open Data Protocol)
- .NET Core日志配置的方法
- 詳解.Net Core中的日志組件(Logging)
- 詳解.Net core2.0日志組件Log4net、Nlog簡(jiǎn)單性能測(cè)試
- .net core日志系統(tǒng)相關(guān)總結(jié)
相關(guān)文章
在.ashx文件中獲取cookies值實(shí)現(xiàn)代碼
.ashx文件中獲取cookies值對(duì)于一些高手們就不多說(shuō)了,至于一些小白們還是有必要多多學(xué)習(xí)啊,好了話不多說(shuō),看代碼,感興趣的你可不要錯(cuò)過(guò)了哈2013-02-02.Net Core中自定義認(rèn)證實(shí)現(xiàn)
本文主要介紹了.Net Core中自定義認(rèn)證實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01asp.net request.PathInfo實(shí)現(xiàn)的url重寫
最近對(duì)在開始研究url重寫,對(duì)重寫的原理以及重寫之后引起的性能問題是研究的重點(diǎn),研究過(guò)程中發(fā)現(xiàn)了一種輕便的“url重寫方案”2009-04-04一步一步學(xué)asp.net Ajax登錄設(shè)計(jì)實(shí)現(xiàn)解析
做一個(gè)登錄,擁有自動(dòng)記住賬號(hào)和密碼的功能,要保證安全性,ajax,無(wú)刷新,良好的用戶體驗(yàn).(母板頁(yè))2012-05-05asp.net gridview分頁(yè):第一頁(yè) 下一頁(yè) 1 2 3 4 上一頁(yè) 最末頁(yè)
這篇文章主要介紹了asp.net gridview分頁(yè):第一頁(yè) 下一頁(yè) 1 2 3 4 上一頁(yè) 最末頁(yè),可使用上下鍵選中行,選中后點(diǎn)擊修改,textbox獲得gridview中的代碼的數(shù)據(jù),需要的朋友可以參考下2014-12-12.NET?6新特性試用之DateOnly和TimeOnly類型
這篇文章主要介紹了.NET?6新特性試用之DateOnly和TimeOnly類型,主要介紹DateOnly和TimeOnly類型使用過(guò)程及存在的一些過(guò)程,需要的小伙伴可以參考一下2022-03-03C#中的cookie編程簡(jiǎn)單實(shí)例與說(shuō)明
這篇文章介紹了C#中的cookie編程簡(jiǎn)單實(shí)例與說(shuō)明,有需要的朋友可以參考一下2013-07-07.Net判斷一個(gè)對(duì)象是否為數(shù)值類型實(shí)例
這篇文章主要介紹了.Net判斷一個(gè)對(duì)象是否為數(shù)值類型的方法,實(shí)例講述了一個(gè)國(guó)外的示例并對(duì)其進(jìn)行了改進(jìn),非常實(shí)用,需要的朋友可以參考下2014-10-10