1、微軟內置的日誌組件git
在.Net Core中使用模板新建的Web Api項目時,會自動加入日誌功能。只須要在控制器中注入ILogger就能夠了。命名空間爲:Microsoft.Extensions.Logging。github
會發現只有Error被打印到了控制檯,Trace沒有被打印。那是由於在appsetting.json中配置了Logging>Console>Default的等級爲Debug,日誌的等級大於等於Debug纔會輸出到控制檯。在這裏說一下LogLevel:Trace<Debug<Information<Warning<Error<Critical<None。數據庫
當打開appsettings.development.json文件你會發現跟appsettings.json配置不一樣。以下:json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
例如:網絡
"System": "Information" 表示命名空間以System開頭的類中且日誌等級大於等於Information纔會輸出到控制檯。app
"Default": "Debug" 表示除以System和Microsoft開頭的命名空間日誌等級大約等於Debug纔會輸出到控制檯。函數
這裏說明一下究竟是在何時,讀取了appsettings.json中的配置了了? 實際上是在Program中 WebHost.CreateDefaultBuilder(arge)。打開源碼發現佈局
固然咱們能夠不用微軟提供的默認配置ui
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"])//設置啓動時的地址 .Build(); host.Run(); } }
配置文件爲:spa
{ "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)//在構造函數中注入 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(); } }
可是微軟提供的內置的日誌組件沒有實現將日誌記錄到文件、數據庫上。下面介紹NLog
2、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}" />//將日誌經過網絡輸出
<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}" 表示爲文件內容的佈局。
rules標籤下面表示,對應等級的日誌寫到對應target中。如
<logger name="*" level="Info" writeTo="infofile" /> 表示等級爲Info的日誌寫到target名稱爲infofile的文件中。
<logger name="*" minlevel="Trace" writeTo="allfile,debuge" /> 表示日誌等級大於Trace的日誌寫到target名稱爲allfile和debuge(控制檯輸出)中。
一樣在使用的時候,只須要在用到的地方注入ILogger,就可使用了。