本篇介紹日誌的使用,包括系統預設的控制台日誌和第三方NLog日誌管理。 ...
系列目錄
本系列涉及到的源碼下載地址:https://github.com/seabluescn/Blog_WebApi
一、本篇概述
本篇介紹日誌的使用,包括系統預設的控制台日誌和第三方NLog日誌管理。
二、使用系統控制台日誌
1、使用內置日誌
[Produces("application/json")] [Route("api/Article")] public class ArticleController : Controller { private readonly ILogger _logger; public ArticleController(SalesContext context, ILogger<ArticleController> logger) { _logger = logger; } [HttpGet("logger")] public void TestLogger() { _logger.LogCritical("LogCritical"); _logger.LogError("LogError"); _logger.LogWarning("LogWarning"); _logger.LogInformation("LogInformation"); _logger.LogDebug("LogDebug"); return; } }
預設只能看到前三條記錄:
主要原因是日誌的最低級別預設為Warring,如果要顯示其他級別日誌,需要修改application.json文件。
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Error"
}
},
"Console": {
"LogLevel": {
"Default": "Infomation"
}
}
}
}
日誌級別優先順序如下順序:
Critical > Error > Warning > Information > Debug
調整日誌級別為Information 或Debug以後會顯示太多無關的日誌信息,可以配置預設級別為Warring,而自己項目命名空間的日誌級別為Debug。
"Console": { "LogLevel": { "Default": "Warning", "SaleService.Controllers": "DEBUG" } }
2、幾點說明
1)目前日誌已經可以正常工作了,把項目發佈到Linux環境下,通過配置Supervisor可以把控制台的內容輸出到文件系統,建議在調試環境下採用Debug日誌級別,而在生成環境採用Error日誌級別。配置Supervisor的內容可以參考:循序漸進學.Net Core Web Api開發系列【7】:項目發佈。
2)如果稍微瞭解依賴註入(DI)的知識,就可以理解我們在Controoler中使用ILogger是採用標準的構造函數註入的方式,但是問題是用戶並沒有註冊該服務,其實是系統在CreateDefaultBuilder時幫我們註冊了日誌服務。可以看幾段源碼的片段:
CreateDefaultBuilder:
using System; using System.IO; using System.Reflection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore { public static class WebHost { public static IWebHostBuilder CreateDefaultBuilder(string[] args) { return WebHostBuilderIISExtensions.UseIISIntegration(HostingAbstractionsWebHostBuilderExtensions.UseContentRoot(WebHostBuilderKestrelExtensions.UseKestrel(new WebHostBuilder()), Directory.GetCurrentDirectory()).ConfigureAppConfiguration(delegate(WebHostBuilderContext hostingContext, IConfigurationBuilder config) { IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment; JsonConfigurationExtensions.AddJsonFile(JsonConfigurationExtensions.AddJsonFile(config, "appsettings.json", true, true), string.Format("appsettings.{0}.json", hostingEnvironment.EnvironmentName), true, true); if (HostingEnvironmentExtensions.IsDevelopment(hostingEnvironment)) { Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName)); if (assembly != null) { UserSecretsConfigurationExtensions.AddUserSecrets(config, assembly, true); } } EnvironmentVariablesExtensions.AddEnvironmentVariables(config); if (args != null) { CommandLineConfigurationExtensions.AddCommandLine(config, args); } }).ConfigureLogging(delegate(WebHostBuilderContext hostingContext, ILoggingBuilder logging) { LoggingBuilderExtensions.AddConfiguration(logging, hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); })).UseDefaultServiceProvider(delegate(WebHostBuilderContext context, ServiceProviderOptions options) { options.ValidateScopes = HostingEnvironmentExtensions.IsDevelopment(context.HostingEnvironment); }); } } }
AddConsole:
using System; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Console; namespace Microsoft.Extensions.Logging { public static class ConsoleLoggerExtensions { public static ILoggingBuilder AddConsole(this ILoggingBuilder builder) { builder.Services.AddSingleton<ILoggerProvider, ConsoleLoggerProvider>(); return builder; } } }
三、使用NLog
1、通過NuGet獲取包:NLog.Web.AspNetCore
2、修改Startup類的Configure方法:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddNLog(); loggerFactory.ConfigureNLog("nlog.config"); //如果採用預設配置文件nlog.config,該語句可以省略 } }
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"> <targets> <target xsi:type="File" name="logfile" fileName="${basedir}/logs/${shortdate}_all.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="debugfile" fileName="${basedir}/logs/${shortdate}_debug.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="errfile" fileName="${basedir}/logs/${shortdate}_error.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" /> </targets> <rules> <logger name="*" level="Debug" writeTo="debugfile" /> <logger name="*" level="Error" writeTo="errfile" /> <logger name="*" minlevel="Trace" writeTo="logfile" /> </rules> </nlog>
項目發佈時修改配置文件,只保留errfile即可。
以上就是全部代碼,Controller中的代碼無需修改。
3、兩個註意點
1)目前我們已經採用NLog來進行日誌的記錄,此時系統預設的日誌仍然是正常工作的,項目發佈時建議把系統預設的日誌級別改成Error,nlog的輸出日誌只保留errfile,以免造成伺服器磁碟空間浪費。
2)項目發佈時nlog.config文件可能不會發佈到目標目錄,需要修改該文件的文件屬性: