1. 程式人生 > >基於.NetCore3.1系列 —— 日誌記錄之日誌配置揭祕

基於.NetCore3.1系列 —— 日誌記錄之日誌配置揭祕

# 一、前言 在專案的開發維護階段,有時候我們關注的問題不僅僅在於功能的實現,甚至需要關注系統釋出上線後遇到的問題能否及時的查詢並解決。所以我們需要有一個好的解決方案來及時的定位錯誤的根源並做出正確及時的修復,這樣才能不影響系統正常的執行狀態。 這個時候我們發現,其實在asp.net core中已經內建了日誌系統,並提供了各種內建和第三方日誌記錄提供程式的日誌記錄介面,在進行應用開發中,可以進行統一配置,並且利用第三方日誌框架相結合,更加有效的實現日誌記錄。所以在這個系列中,主要是對內建日誌記錄系統的學習,以及後續使用第三方日誌框架整合我們需要的日誌系統。 # 二、說明 在這一篇中主要是對日誌記錄的配置進行說明,從開始配置日誌,以及後續使用配置進行日誌處理。 在新建專案成功之後,我們都會看到一個命名為`appsettings.json`配置,開啟一看,短短的幾行配置, ```json "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, ``` 然後啟動執行的時候,程式會在除錯面板和控制檯中分別輸出顯示來源如下: 在控制檯中: ![logging](https://img2020.cnblogs.com/blog/1576550/202007/1576550-20200731193603821-1240776226.png) 在除錯面板中: ![img](https://img2020.cnblogs.com/blog/1576550/202007/1576550-20200731193623232-2102907278.png) 這裡的日誌配置,在系統中到底都起來什麼作用?讓我們來一探究竟吧! # 三、開始 ## 3.1 預設配置 我們檢視原始碼發現,在程式的入口點中發現,在初始化時候,通過`CreateDefaultBuilder`方法來實現日誌記錄的預設配置。 ```c# public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); } ``` 所以下面我們看一下`CreateDefaultBuilder`在原始碼中都對日誌做了哪些預設配置? ```c# public static IHostBuilder CreateDefaultBuilder(string[] args) { var builder = new HostBuilder(); builder.UseContentRoot(Directory.GetCurrentDirectory()); builder.ConfigureHostConfiguration(config => { config.AddEnvironmentVariables(prefix: "DOTNET_"); if (args != null) { config.AddCommandLine(args); } }); builder.ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName)) { var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); } } config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) .ConfigureLogging((hostingContext, logging) => { var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (isWindows) { logging.AddFilter(level => level >= LogLevel.Warning); } logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); logging.AddEventSourceLogger(); if (isWindows) { logging.AddEventLog(); } }) .UseDefaultServiceProvider((context, options) => { var isDevelopment = context.HostingEnvironment.IsDevelopment(); options.ValidateScopes = isDevelopment; options.ValidateOnBuild = isDevelopment; }); return builder; } ``` 通過上面這一段原始碼我們可以看到一個命名為`ConfigureLogging`的物件,我們根據命名的意思大致可以看出,這是一個配置日誌的方法,繼續檢視`ConfigureLogging`原始碼 ```c# public static IHostBuilder ConfigureLogging(this IHostBuilder hostBuilder, Action configureLogging) { return hostBuilder.ConfigureServices((context, collection) => collection.AddLogging(builder => configureLogging(context, builder))); } ``` 通過`IServiceCollection`註冊服務集合容器,將日誌服務新增到這個服務容器,使用`AddLogging`方法實現對日誌服務的註冊。 ```c# public static IServiceCollection AddLogging(this IServiceCollection services, Action configure) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddOptions(); services.TryAdd(ServiceDescriptor.Singleton()); services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>))); services.TryAddEnumerable(ServiceDescriptor.Singleton>( new DefaultLoggerLevelConfigureOptions(LogLevel.Information))); configure(new LoggingBuilder(services)); return services; } ``` 通過`AddLogging`新增到服務集合容器,先通過新增所需的配置`AddOptions`,通過注入的方式實現預設的`ILoggerFactory`,`ILogger` ( 這個會在後續的篇章中進行說明),再後通過`LoggingBuilder`完成日誌物件的建立, ```c# public interface ILoggingBuilder { IServiceCollection Services { get; } } internal class LoggingBuilder : ILoggingBuilder { public LoggingBuilder(IServiceCollection services) { Services = services; } public IServiceCollection Services { get; } } ``` 對日誌系統的配置,用於提供程式的介面,`ILoggingBuilder`後面可以對該物件進行拓展使用。 通過以上的流程`CreateDefaultBuilder`方法,實現對預先配置的預設值初始化,因此也發現了其中的`ConfigureLogging`也是其中要進行預設初始化的值,也就是系統預設的日誌配置。 單獨把`ConfigureLogging`這一塊的原始碼拎出來再看看: ```c# .ConfigureLogging((hostingContext, logging) => { var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (isWindows) { logging.AddFilter(level => level >= LogLevel.Warning); } logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); logging.AddEventSourceLogger(); if (isWindows) { logging.AddEventLog(); } }) ``` 在asp.net core啟動中,根據作業系統平臺適應不同的服務,在windows服務中,將`EventLogLoggerProvider`的預設值設定為警告或者更高的級別。 **AddConfiguration** : 新增系統日誌的全域性配置。 在配置中,可以根據提供的不同型別程式來針對實現日誌記錄的輸出方式。而這裡預設實現的`AddConsole()`、`AddDebug`() 和`AddEventSourceLogger()`分別是將日誌輸出到控制檯、除錯視窗中,以及提供寫入事件源。 **AddConsole** : 新增控制檯到工廠方法中,用來將日誌記錄到控制檯中。 **AddDebug** : 新增Debug視窗到工廠方法中,用來將日誌記錄到視窗中。 > 說明:asp.net core 內建的日誌介面中,實現了多種內建的日誌提供器,除了上面預設實現的`Console`、`Debug`和`EventSource`,還包括下面的這幾個 > > EventLog : > > TraceSource > > AzureAppServicesFile > > AzureAppServicesBlob > > ApplicationInsights 還記得上面提到的`appsettings.json`配置嗎?在這裡,我們來看看 ```json { "Logging": { "LogLevel": { "Default": "Debug", "Microsoft": "Information" }, "Console": { "LogLevel": { "Default": "Debug", "System": "Warning" } } } } ``` 在`AddConfiguration`中, ```c# logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); ``` 獲取配置檔案的`Logging`資料,實現全域性配置, ```c# public static ILoggingBuilder AddConfiguration(this ILoggingBuilder builder, IConfiguration configuration) { builder.AddConfiguration(); builder.Services.AddSingleton>(new LoggerFilterConfigureOptions(configuration)); builder.Services.AddSingleton>(new ConfigurationChangeTokenSource(configuration)); builder.Services.AddSingleton(new LoggingConfiguration(configuration)); return builder; } internal class LoggerFilterConfigureOptions : IConfigureOptions { private const string LogLevelKey = "LogLevel"; private const string DefaultCategory = "Default"; private readonly IConfiguration _configuration; public LoggerFilterConfigureOptions(IConfiguration configuration) { _configuration = configuration; } public void Configure(LoggerFilterOptions options) { LoadDefaultConfigValues(options); } private void LoadDefaultConfigValues(LoggerFilterOptions options) { if (_configuration == null) { return; } options.CaptureScopes = _configuration.GetValue(nameof(options.CaptureScopes), options.CaptureScopes); foreach (var configurationSection in _configuration.GetChildren()) { if (configurationSection.Key.Equals(LogLevelKey, StringComparison.OrdinalIgnoreCase)) { // Load global category defaults LoadRules(options, configurationSection, null); } else { var logLevelSection = configurationSection.GetSection(LogLevelKey); if (logLevelSection != null) { // Load logger specific rules var logger = configurationSection.Key; LoadRules(options, logLevelSection, logger); } } } } private void LoadRules(LoggerFilterOptions options, IConfigurationSection configurationSection, string logger) { foreach (var section in configurationSection.AsEnumerable(true)) { if (TryGetSwitch(section.Value, out var level)) { var category = section.Key; if (category.Equals(DefaultCategory, StringComparison.OrdinalIgnoreCase)) { category = null; } var newRule = new LoggerFilterRule(logger, category, level, null); options.Rules.Add(newRule); } } } } ``` 以上是`AddConfiguration`實現的整體流程原始碼,預設註冊實現`LoggerFilterConfigureOptions`對配置資料的讀取,其中定義的 **LogLevelKey = "LogLevel"** 、**DefaultCategory = "Default"** 預設字串,以此來獲取預設全域性配置資料。 在預設配置的文字格式`appsettings.json`中,`Logging`屬性可以具有`LogLevel`和日誌提供程式屬性。`Logging` 下的 `LogLevel` 屬性指定了用於記錄所選類別的最低級別。在本例中, `Microsoft` 類別在 `Information` 級別記錄,其他均在 `Debug` 級別記錄。 > **日誌級別說明**:每一個日誌都有指定的日誌級別值,日誌級別判斷指示嚴重性或重要性。使用日誌等級可以很好的過濾想要的日誌,記錄日誌記錄問題的同時,甚至為我們提供非常詳細的日誌資訊。 > > **LogLevel 嚴重性:Trace < Debug < Information < Warning < Error < Critical < None。** > > | 日誌級別 | 常用場景 | > | ------------------- | ------------------------------------------------------------ | > | **Trace = 0** | 記錄一些對程式設計師除錯問題有幫助的資訊, 其中可能包含一些敏感資訊, 所以應該避免在 生產環境中啟用Trace日誌,因此不應該用於生產環境。預設應禁用。 | > | **Debug = 1** | 記錄一些在開發和除錯階段有用的短時變 量(Short-term usefulness), 所以除非為了臨時排除生產環境的 故障,開發人員應該儘量避免在生產環境中啟用Debug日誌,預設情況下這是最詳細的日誌。 | > | **Information = 2** | 記錄跟蹤應用程式的一些流程, 例如,記錄當前api請求的url。 | > | **Warning = 3** | 記錄應用程式中發生出現錯誤或其它導致程式停止的流程異常資訊。 這些資訊中可能包含錯誤訊息或者錯誤產生的條件, 可供後續調查,例如, 檔案未找到 | > | **Error = 4** | 記錄應用程式中某個操作產生的錯誤和異常資訊。這些訊息應該指明當前活動或操作(比如當前的 HTTP 請求),而不是應用程式範圍的故障。 | > | **Critical = 5** | 記錄一些需要立刻修復,急需被關注的問題,應當記錄關鍵級別的日誌。例如資料丟失,磁碟空間不足等。 | > > 日誌級別只需要簡單的通過 `AddFilter` 對日誌的過濾級別配置一下就行了。同時也可以通過自定義在 > > 在 `Logging.{providername}.LogLevel` 中指定了級別,則這些級別將重寫 `Logging.LogLevel` 中設定的所有內容。(在下文自定義中說明) 由此可以看出,日誌記錄提供程式配置由一個或多個配置提供程式提供,如檔案格式(系統自帶的`appsettings.json`)或者通過(已安裝或已建立的)自定義提供程式(下文會說明自定義方式)。 ## 3.2 自定義配置 看完了上面實現的預設配置之後,我們也清楚了可以修改預設配置實現不同等級日誌的輸出,因此,我們也可以通過自定義的方式,對預設配置的修改,實現我們想要的日誌記錄方式。 可以通過自行選擇新增提供程式來替換預設配置的提供的程式。這樣就實現自定義。自定義的方式有很多,比如 ### 3.2.1 程式碼新增提供程式 呼叫`ClearProviders`,清除預設之後,可新增所需的提供程式。如下: ```c# public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) //可以看出在使用模板建立專案的時候,預設添加了控制檯和除錯日誌元件,並從appsettings.json中讀取配置。 .ConfigureLogging((hostingContext, logging) => { logging.ClearProviders(); //去掉預設新增的日誌提供程式 //新增控制檯輸出 logging.AddConsole(); //新增除錯輸出 logging.AddDebug(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); } ``` 由上可以發現我們可以通過在入口程式中直接對新增`ConfigureLogging`(在上文中原始碼可以看出)拓展方法來實現我們的自定義配置。 ### 3.2.2 程式碼新增過濾器 過濾器`AddFilter`,新增過濾規則,可以為不同的日誌提供者指定不同的過濾器,實現有效的自定義日誌的輸出。如下程式碼: ```c# .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter("Microsoft", LogLevel.Trace)) ``` 新增指定了全域性的過濾器,作用於所有日誌提供者,示例中的第二個 `AddFilter` 使用型別名稱來指定除錯提供程式。 第一個 `AddFilter` 應用於全部提供程式,因為它未指定提供程式型別。 這裡的`AddFilter`其實於之前讀取配置檔案資訊新增配置`AddConfiguration`的作用相似,只是從配置檔案的邏輯改成了以程式碼的方式實現過濾篩選,到最終也是對`ConfigureOptions `的配置。 ### 3.2.3 配置檔案自定義 ASP.NET Core預設會從appSetting.json中的Logging屬性讀取日誌的配置(當然你也可以從其他檔案中讀取配置),這裡設定了不同的日誌提供器產生的最低的日誌級別,配置樣例如下。 ```json { "Logging": { "Debug": { "LogLevel": { "Default": "Information" } }, "Console": { "LogLevel": { "Microsoft.AspNetCore.Mvc.Razor.Internal": "Warning", "Microsoft.AspNetCore.Mvc.Razor.Razor": "Debug", "Microsoft.AspNetCore.Mvc.Razor": "Error", "Default": "Information" } }, "LogLevel": { "Default": "Debug" } } } ``` 此 JSON 將建立 6 條篩選規則:`Debug`中1 條用於除錯提供程式,`Console`中 4 條用於控制檯提供程式,最後一條`LogLevel` 用於所有提供程式。 建立 `ILogger` 物件時,為每個提供程式選擇一個規則。 # 四、問題 雖然在這一節中只是對日誌記錄的配置進行了說明,但是在後續中也會對日誌內部的核心執行機制進行說明介紹。所以,在這一篇中留下幾個疑問 1. 日誌記錄的輸出可以在哪裡檢視?而又由什麼實現決定的呢? 2. 如何管理輸出不同的日誌呢?都有哪些方式呢? 以上的這些內容,會在下一篇進行介紹說明。 好了,今天的日誌配置內容就說到這裡了,希望能給大家在使用Core開發專案中對日誌系統有進一步的認識。 # 五、總結 1. 本篇主要是對net core3.1中內建的系統日誌進行配置使用,不管是基於預設配置的輸出方式,還是自定義形式的配置,都是為了有效的輸出日誌記錄,便於我們查詢發現問題。 2. 關於日誌配置,其實都是在對`ConfigureOptions`的配置,只是在形式上是直接讀取配置檔案或通過程式碼的方式實現自定義來實現日誌配置。 3. 後續會對內建的日誌系統進一步說明,以及內部執行的主要核心機制。 4. 如果有不對的或不理解的地方,希望大家可以多多指正,提出問題,一起討論,不斷學習,共同進步。 5. 官方[原始碼](https://github.com/dotnet/extensions/tree/master/src/Logging) 和 [參考資料](https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/logging/?view=aspnetc