詳解.Net Core中的日志組件(Logging)
1、介紹
Logging組件是微軟實(shí)現(xiàn)的日志記錄組件包括控制臺(tái)(Console)、調(diào)試(Debug)、事件日志(EventLog)和TraceSource,但是沒有實(shí)現(xiàn)最常用用的文件記錄日志功能(可以用其他第三方的如NLog、Log4Net。之前寫過NLog使用的文章)。
2、默認(rèn)配置
新建.Net Core Web Api項(xiàng)目,添加下面代碼。
[Route("api/[controller]")] public class ValuesController : Controller { ILogger<ValuesController> logger; //構(gòu)造函數(shù)注入Logger public ValuesController(ILogger<ValuesController> logger) { this.logger = logger; } [HttpGet] public IEnumerable<string> Get() { logger.LogWarning("Warning"); return new string[] { "value1", "value2" }; } }
運(yùn)行結(jié)果如下:
我剛開始接觸的時(shí)候,我就有一個(gè)疑問我根本沒有配置關(guān)于Logger的任何代碼,僅僅寫了注入,為什么會(huì)起作用呢?最后我發(fā)現(xiàn)其實(shí)是在Program類中使用了微軟默認(rèn)的配置。
public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args)//在這里使用了默認(rèn)配置 .UseStartup<Startup>() .Build(); }
下面為CreateDefaultBuilder方法的部分源碼,整個(gè)源碼在 https://github.com/aspnet/MetaPackages ,可以看出在使用模板創(chuàng)建項(xiàng)目的時(shí)候,默認(rèn)添加了控制臺(tái)和調(diào)試日志組件,并從appsettings.json中讀取配置。
builder.UseKestrel((builderContext, options) => { options.Configure(builderContext.Configuration.GetSection("Kestrel")); }) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; //加載appsettings.json文件 使用模板創(chuàng)建的項(xiàng)目,會(huì)生成一個(gè)配置文件,配置文件中包含Logging的配置項(xiàng) config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); ....... }) .ConfigureLogging((hostingContext, logging) => { //從appsettings.json中獲取Logging的配置 logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); //添加控制臺(tái)輸出 logging.AddConsole(); //添加調(diào)試輸出 logging.AddDebug(); })
3、建立自己的Logging配置
首先修改Program類
public class Program { public static void Main(string[] args) { //指定配置文件路徑 var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory())//設(shè)置基礎(chǔ)路徑 .AddJsonFile($"appsettings.json", true, true)//加載配置文件 .AddJsonFile($"appsettings.{EnvironmentName.Development}.json", true, true) .Build(); var host = new WebHostBuilder() .UseKestrel() .UseStartup<Startup>() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(config)//使用配置 .UseUrls(config["AppSettings:Url"])//從配置中讀取 程序監(jiān)聽的端口號(hào) .UseEnvironment(EnvironmentName.Development)//如果加載了多個(gè)環(huán)境配置,可以設(shè)置使用哪個(gè)配置 一般有測(cè)試環(huán)境、正式環(huán)境 //.ConfigureLogging((hostingCotext, logging) => //第一種配置方法 直接在webHostBuilder建立時(shí)配置 不需要修改下面的Startup代碼 //{ // logging.AddConfiguration(hostingCotext.Configuration.GetSection("Logging")); // logging.AddConsole(); //}) .Build(); host.Run(); } }
修改Startup類如下面,此類的執(zhí)行順序?yàn)?strong> Startup構(gòu)造函數(shù) > ConfigureServices > Configure
public class Startup { public IConfiguration Configuration { get; private set; } public IHostingEnvironment HostingEnvironment { get; private set; } //在構(gòu)造函數(shù)中注入 IHostingEnvironment和IConfiguration,配置已經(jīng)在Program中設(shè)置了,注入后就可以獲取配置文件的數(shù)據(jù) public Startup(IHostingEnvironment env, IConfiguration config) { HostingEnvironment = env; Configuration = config; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //第二種配置 也可以這樣加上日志功能,不用下面的注入 //services.AddLogging(builder => //{ // builder.AddConfiguration(Configuration.GetSection("Logging")) // .AddConsole(); //}); } //注入ILoggerFactory public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //第三種配置 注入ILogggerFactory,然后配置參數(shù) //添加控制臺(tái)輸出 loggerFactory.AddConsole(Configuration.GetSection("Logging")); //添加調(diào)試輸出 loggerFactory.AddDebug(); app.UseMvc(); } }
這種結(jié)構(gòu)就比較清晰明了。
4、Logging源碼解析
三種配置其實(shí)都是為了注入日志相關(guān)的服務(wù),但是調(diào)用的方法稍有不同?,F(xiàn)在我們以第二種配置來詳細(xì)看看其注入過程。首先調(diào)用AddLogging方法,其實(shí)現(xiàn)源碼如下:
public static IServiceCollection AddLogging(this IServiceCollection services, Action<ILoggingBuilder> configure) { services.AddOptions();//這里會(huì)注入最基礎(chǔ)的5個(gè)服務(wù) option相關(guān)服務(wù)只要是跟配置文件相關(guān),通過Option服務(wù)獲取相關(guān)配置文件參數(shù)參數(shù) services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>()); services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>))); services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<LoggerFilterOptions>>(new DefaultLoggerLevelConfigureOptions(LogLevel.Information))); configure(new LoggingBuilder(services)); return services; }
接著會(huì)調(diào)用AddConfiguration
public static ILoggingBuilder AddConfiguration(this ILoggingBuilder builder, IConfiguration configuration) { builder.AddConfiguration(); //下面為AddConfiguration的實(shí)現(xiàn) public static void AddConfiguration(this ILoggingBuilder builder) { builder.Services.TryAddSingleton<ILoggerProviderConfigurationFactory, LoggerProviderConfigurationFactory>(); builder.Services.TryAddSingleton(typeof(ILoggerProviderConfiguration<>), typeof(LoggerProviderConfiguration<>)); } builder.Services.AddSingleton<IConfigureOptions<LoggerFilterOptions>>(new LoggerFilterConfigureOptions(configuration)); builder.Services.AddSingleton<IOptionsChangeTokenSource<LoggerFilterOptions>>(new ConfigurationChangeTokenSource<LoggerFilterOptions>(configuration)); builder.Services.AddSingleton(new LoggingConfiguration(configuration)); return builder; }
下面來看打印日志的具體實(shí)現(xiàn):
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { var loggers = Loggers; List<Exception> exceptions = null; //loggers為L(zhǎng)oggerInformation數(shù)組,如果你在Startup中添加了Console、Deubg日志功能了,那loggers數(shù)組值有2個(gè),就是它倆。 foreach (var loggerInfo in loggers) { //循環(huán)遍歷每一種日志打印,如果滿足些日子的條件,才執(zhí)行打印log方法。比如某一個(gè)日志等級(jí)為Info, //但是Console配置的最低打印等級(jí)為Warning,Debug配置的最低打印等級(jí)為Debug //則Console中不會(huì)打印,Debug中會(huì)被打印 if (!loggerInfo.IsEnabled(logLevel)) { continue; } try { //每一種類型的日志,對(duì)應(yīng)的打印方法不同。執(zhí)行對(duì)應(yīng)的打印方法 loggerInfo.Logger.Log(logLevel, eventId, state, exception, formatter); } catch (Exception ex) { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(ex); } } }
下面具體看一下Console的打印實(shí)現(xiàn):
首先ConsoleLogger實(shí)現(xiàn)了ILogger的Log方法,并在方法中調(diào)用WriteMessage方法
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { //代碼太多 我就省略一些判空代碼 var message = formatter(state, exception); if (!string.IsNullOrEmpty(message) || exception != null) { WriteMessage(logLevel, Name, eventId.Id, message, exception); } } public virtual void WriteMessage(LogLevel logLevel, string logName, int eventId, string message, Exception exception) { ....... if (logBuilder.Length > 0) { var hasLevel = !string.IsNullOrEmpty(logLevelString); //這里是主要的代碼實(shí)現(xiàn),可以看到,并沒有寫日志的代碼,而是將日志打入到一個(gè)BlockingCollection<LogMessageEntry>隊(duì)列中 _queueProcessor.EnqueueMessage(new LogMessageEntry() { Message = logBuilder.ToString(), MessageColor = DefaultConsoleColor, LevelString = hasLevel ? logLevelString : null, LevelBackground = hasLevel ? logLevelColors.Background : null, LevelForeground = hasLevel ? logLevelColors.Foreground : null }); } ...... }
下面看日志被放入隊(duì)列后的具體實(shí)現(xiàn):
public class ConsoleLoggerProcessor : IDisposable { private const int _maxQueuedMessages = 1024; private readonly BlockingCollection<LogMessageEntry> _messageQueue = new BlockingCollection<LogMessageEntry>(_maxQueuedMessages); private readonly Thread _outputThread; public IConsole Console; public ConsoleLoggerProcessor() { //在構(gòu)造函數(shù)中啟動(dòng)一個(gè)線程,執(zhí)行ProcessLogQueue方法 //從下面ProcessLogQueue方法可以看出,是循環(huán)遍歷集合,將集合中的數(shù)據(jù)打印 _outputThread = new Thread(ProcessLogQueue) { IsBackground = true, Name = "Console logger queue processing thread"public virtual void EnqueueMessage(LogMessageEntry message) { if (!_messageQueue.IsAddingCompleted) { try { _messageQueue.Add(message); return; } catch (InvalidOperationException) { } } WriteMessage(message); } internal virtual void WriteMessage(LogMessageEntry message) { if (message.LevelString != null) { Console.Write(message.LevelString, message.LevelBackground, message.LevelForeground); } Console.Write(message.Message, message.MessageColor, message.MessageColor); Console.Flush(); } private void ProcessLogQueue() { try { //GetConsumingEnumerable()方法比較特殊,當(dāng)集合中沒有值時(shí),會(huì)阻塞自己,一但有值了,知道集合中又有元素繼續(xù)遍歷 foreach (var message in _messageQueue.GetConsumingEnumerable()) { WriteMessage(message); } } catch { try { _messageQueue.CompleteAdding(); } catch { } } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Asp.net GridView隔行變色和光棒效果2種方法實(shí)現(xiàn)
兩種方法實(shí)現(xiàn)GridView隔行變色和光棒效果:前臺(tái)和后臺(tái)配合使用及JQuery方式,感興趣的朋友可以參考下哈,希望可以幫助到你2013-04-04.NET6環(huán)境下實(shí)現(xiàn)MQTT通信及詳細(xì)代碼演示
本文詳細(xì)講解了.NET6環(huán)境下實(shí)現(xiàn)MQTT通信的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07ASP.NET使用ajax實(shí)現(xiàn)分頁局部刷新頁面功能
使用ajax方法實(shí)現(xiàn)分頁也很簡(jiǎn)單,主要是兩個(gè),ContentTemplate和Trigger。先把listView扔ContentTemplate里面。然后在Trigger里面加入asp:AsyncPostBackTrigger,將ID指向之前的分頁控件DataPager控件。具體實(shí)現(xiàn)代碼大家可以參考下本文2017-03-03基于MVC5中的Model層開發(fā)數(shù)據(jù)注解
下面小編就為大家分享一篇基于MVC5中的Model層開發(fā)數(shù)據(jù)注解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12分享AjaxPro或者Ajax實(shí)現(xiàn)機(jī)制
今天與大家分享AjaxPro或者Ajax實(shí)現(xiàn)機(jī)制,需要的朋友可以參考下。2011-12-12.Net中導(dǎo)出數(shù)據(jù)到Excel(asp.net和winform程序中)
.Net中導(dǎo)出數(shù)據(jù)到Excel包括以下兩種情況:asp.net中導(dǎo)出Excel的方法/winForm中導(dǎo)出Excel的方法,針對(duì)以上兩種情況做了下詳細(xì)的實(shí)現(xiàn)代碼,感興趣的朋友可不要錯(cuò)過了哈,希望本文對(duì)你有所幫助2013-02-02