.Net Core項目如何添加日志功能詳解
一、微軟內(nèi)置的日志組件
在.Net Core中使用模板新建的Web Api項目時,會自動加入日志功能。只需要在控制器中注入ILogger就可以了。命名空間為:Microsoft.Extensions.Logging。

會發(fā)現(xiàn)只有Error被打印到了控制臺,Trace沒有被打印。那是因為在appsetting.json中配置了Logging>Console>Default的等級為Debug,日志的等級大于等于Debug才會輸出到控制臺。在這里說一下LogLevel:Trace<Debug<Information<Warning<Error<Critical<None。
當(dāng)打開appsettings.development.json文件你會發(fā)現(xiàn)跟appsettings.json配置不同。如下:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
例如:
"System": "Information" 表示命名空間以System開頭的類中且日志等級大于等于Information才會輸出到控制臺。
"Default": "Debug" 表示除以System和Microsoft開頭的命名空間日志等級大約等于Debug才會輸出到控制臺。
這里說明一下到底是在什么時候,讀取了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è)置啟動時的地址
.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();
}
//添加控制臺輸出
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
但是微軟提供的內(nèi)置的日志組件沒有實(shí)現(xiàn)將日志記錄到文件、數(shù)據(jù)庫上。下面介紹NLog
二、NLog
首先使用NuGet添加NLog,然后在Startup的Configure中添加以下代碼
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//添加控制臺輸出
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}" />//將日志通過網(wǎng)絡(luò)輸出
<target name="debuge" xsi:type="Console"/>//將日志輸出到控制臺
</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”存儲日志為文件格式 ,
xsi:type="Console" 表示為控制臺輸出。
fileName="./logs/${shortdate}/all.log" 表示存儲文件路徑。
layout="${longdate}|${message} ${exception}" 表示為文件內(nèi)容的布局。
rules標(biāo)簽下面表示,對應(yīng)等級的日志寫到對應(yīng)target中。如
<logger name="*" level="Info" writeTo="infofile" /> 表示等級為Info的日志寫到target名稱為infofile的文件中。
<logger name="*" minlevel="Trace" writeTo="allfile,debuge" /> 表示日志等級大于Trace的日志寫到target名稱為allfile和debuge(控制臺輸出)中。
同樣在使用的時候,只需要在用到的地方注入ILogger,就可以使用了。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
- .net core日志結(jié)構(gòu)化
- .net core 使用阿里云分布式日志的配置方法
- ASP.NET Core擴(kuò)展庫之Http日志的使用詳解
- ASP.NET Core擴(kuò)展庫之日志功能的使用詳解
- .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簡單性能測試
- .net core日志系統(tǒng)相關(guān)總結(jié)
相關(guān)文章
在.ashx文件中獲取cookies值實(shí)現(xiàn)代碼
.ashx文件中獲取cookies值對于一些高手們就不多說了,至于一些小白們還是有必要多多學(xué)習(xí)啊,好了話不多說,看代碼,感興趣的你可不要錯過了哈2013-02-02
.Net Core中自定義認(rèn)證實(shí)現(xiàn)
本文主要介紹了.Net Core中自定義認(rèn)證實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
asp.net request.PathInfo實(shí)現(xiàn)的url重寫
最近對在開始研究url重寫,對重寫的原理以及重寫之后引起的性能問題是研究的重點(diǎn),研究過程中發(fā)現(xiàn)了一種輕便的“url重寫方案”2009-04-04
一步一步學(xué)asp.net Ajax登錄設(shè)計實(shí)現(xiàn)解析
做一個登錄,擁有自動記住賬號和密碼的功能,要保證安全性,ajax,無刷新,良好的用戶體驗.(母板頁)2012-05-05
asp.net gridview分頁:第一頁 下一頁 1 2 3 4 上一頁 最末頁
這篇文章主要介紹了asp.net gridview分頁:第一頁 下一頁 1 2 3 4 上一頁 最末頁,可使用上下鍵選中行,選中后點(diǎn)擊修改,textbox獲得gridview中的代碼的數(shù)據(jù),需要的朋友可以參考下2014-12-12
.NET?6新特性試用之DateOnly和TimeOnly類型
這篇文章主要介紹了.NET?6新特性試用之DateOnly和TimeOnly類型,主要介紹DateOnly和TimeOnly類型使用過程及存在的一些過程,需要的小伙伴可以參考一下2022-03-03

