.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沒(méi)有被打印。那是因?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)打開(kāi)appsettings.development.json文件你會(huì)發(fā)現(xiàn)跟appsettings.json配置不同。如下:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
例如:
"System": "Information" 表示命名空間以System開(kāi)頭的類(lèi)中且日志等級(jí)大于等于Information才會(huì)輸出到控制臺(tái)。
"Default": "Debug" 表示除以System和Microsoft開(kāi)頭的命名空間日志等級(jí)大約等于Debug才會(huì)輸出到控制臺(tái)。
這里說(shuō)明一下到底是在什么時(shí)候,讀取了appsettings.json中的配置了了? 其實(shí)是在Program中 WebHost.CreateDefaultBuilder(arge) 。
打開(kāi)源碼發(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)置的日志組件沒(mé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í)的日志寫(xiě)到對(duì)應(yīng)target中。如
<logger name="*" level="Info" writeTo="infofile" /> 表示等級(jí)為Info的日志寫(xiě)到target名稱(chēng)為infofile的文件中。
<logger name="*" minlevel="Trace" writeTo="allfile,debuge" /> 表示日志等級(jí)大于Trace的日志寫(xiě)到target名稱(chēng)為allfile和debuge(控制臺(tái)輸出)中。
同樣在使用的時(shí)候,只需要在用到的地方注入ILogger,就可以使用了。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(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開(kāi)發(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)文章
asp.net中引用同一個(gè)項(xiàng)目中的類(lèi)庫(kù) 避免goToDefinition時(shí)不能到達(dá)真正的定義類(lèi)
asp.net中引用同一個(gè)項(xiàng)目中的類(lèi)庫(kù) 避免 goToDefinition時(shí)不能到達(dá)真正的定義類(lèi)2011-10-10
使用Blazor框架實(shí)現(xiàn)在前端瀏覽器中導(dǎo)入和導(dǎo)出Excel
Blazor?是一個(gè)相對(duì)較新的框架,用于構(gòu)建具有?.NET?強(qiáng)大功能的交互式客戶(hù)端?Web?UI,本文主要介紹了如何在?Blazor?應(yīng)用程序中實(shí)現(xiàn)?SpreadJS?利用?.NET?的強(qiáng)大功能完成瀏覽器端的?Excel?導(dǎo)入導(dǎo)出,需要的可以參考一下2023-05-05
VS2012/VS2013本地發(fā)布網(wǎng)站步驟詳解
這篇文章主要介紹了VS2012/VS2013本地發(fā)布網(wǎng)站的詳細(xì)步驟,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
.Net基于MVC4 Web Api輸出Json格式實(shí)例
這篇文章主要介紹了.Net基于MVC4 Web Api輸出Json格式的實(shí)現(xiàn)方法,實(shí)例講述了Global中json的操作與XML的處理等技巧,需要的朋友可以參考下2014-10-10
ASP.NET Core Web中使用AutoMapper進(jìn)行對(duì)象映射
AutoMapper是一個(gè)簡(jiǎn)單易用的.NET對(duì)象映射庫(kù),用于快速、方便地進(jìn)行對(duì)象之間的轉(zhuǎn)換和映射,極大的簡(jiǎn)化了開(kāi)發(fā)人員在處理對(duì)象映射時(shí)的工作量,今天我們來(lái)講講在ASP.NET Core Web中使用AutoMapper快速進(jìn)行對(duì)象映射,感興趣的朋友跟隨小編一起看看吧2024-05-05
gridview實(shí)現(xiàn)服務(wù)器端和客戶(hù)端全選的兩種方法分享
這篇文章主要介紹了gridview實(shí)現(xiàn)服務(wù)器端和客戶(hù)端全選的兩種方法,需要的朋友可以參考下2014-02-02
asp.net模板引擎Razor調(diào)用外部方法用法實(shí)例
這篇文章主要介紹了asp.net模板引擎Razor調(diào)用外部方法用法,實(shí)例分析了Razor調(diào)用外部方法的相關(guān)使用技巧,需要的朋友可以參考下2015-06-06

