這篇文章將為大家詳細(xì)講解有關(guān).Net Core中的日志組件是什么,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
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 { } } } }
關(guān)于.Net Core中的日志組件是什么就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
新聞名稱:.NetCore中的日志組件是什么-創(chuàng)新互聯(lián)
本文鏈接:http://jinyejixie.com/article10/dsehgo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、Google、關(guān)鍵詞優(yōu)化、網(wǎng)站收錄、商城網(wǎng)站、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容