.Net Core中的日誌組件(Logging)

一、介紹

  Logging組件是微軟實現的日誌記錄組件包括控制檯(Console)、調試(Debug)、事件日誌(EventLog)和TraceSource,可是沒有實現最經常使用用的文件記錄日誌功能(能夠用其餘第三方的如NLog、Log4Net。以前寫過NLog使用的文章)。html

二、默認配置

  新建.Net Core Web Api項目,添加下面代碼。git

    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        ILogger<ValuesController> logger;
     //構造函數注入Logger
public ValuesController(ILogger<ValuesController> logger) { this.logger = logger; } [HttpGet] public IEnumerable<string> Get() { logger.LogWarning("Warning"); return new string[] { "value1", "value2" }; } }

 運行結果以下:github

 

我剛開始接觸的時候,我就有一個疑問我根本沒有配置關於Logger的任何代碼,僅僅寫了注入,爲何會起做用呢?最後我發現實際上是在Program類中使用了微軟默認的配置。web

public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }
        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)//在這裏使用了默認配置
                .UseStartup<Startup>()
                .Build();
    }

 下面爲CreateDefaultBuilder方法的部分源碼,整個源碼在 https://github.com/aspnet/MetaPackages,能夠看出在使用模板建立項目的時候,默認添加了控制檯和調試日誌組件,並從appsettings.json中讀取配置。json

                builder.UseKestrel((builderContext, options) =>
                {
                    options.Configure(builderContext.Configuration.GetSection("Kestrel"));
                })
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var env = hostingContext.HostingEnvironment;
            //加載appsettings.json文件 使用模板建立的項目,會生成一個配置文件,配置文件中包含Logging的配置項
                    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"));
            //添加控制檯輸出 logging.AddConsole();
            //添加調試輸出 logging.AddDebug(); })

 三、創建本身的Logging配置

  首先修改Program類api

public class Program
    {
        public static void Main(string[] args)
        {
            //指定配置文件路徑
            var config = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())//設置基礎路徑
                                .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"])//從配置中讀取 程序監聽的端口號
                        .UseEnvironment(EnvironmentName.Development)//若是加載了多個環境配置,能夠設置使用哪一個配置 通常有測試環境、正式環境

              //.ConfigureLogging((hostingCotext, logging) => //第一種配置方法 直接在webHostBuilder創建時配置 不須要修改下面的Startup代碼
              //{
              //    logging.AddConfiguration(hostingCotext.Configuration.GetSection("Logging"));
              //    logging.AddConsole();
              //})數組

                        .Build();
            host.Run();
        }
    }

修改Startup類以下面,此類的執行順序爲 Startup構造函數 > ConfigureServices > Configure安全

public class Startup
    {
        public IConfiguration Configuration { get; private set; }
        public IHostingEnvironment HostingEnvironment { get; private set; }
        //在構造函數中注入 IHostingEnvironment和IConfiguration,配置已經在Program中設置了,注入後就能夠獲取配置文件的數據
        public Startup(IHostingEnvironment env, IConfiguration config)
        {
            HostingEnvironment = env;
            Configuration = config;
        }
        public void ConfigureServices(IServiceCollection services)
        {

        services.AddMvc();app

        //第二種配置 也能夠這樣加上日誌功能,不用下面的注入
        //services.AddLogging(builder => 
        //{
          // builder.AddConfiguration(Configuration.GetSection("Logging"))
          //        .AddConsole();
        //});ide

        }
     //注入ILoggerFactory 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
       //第三種配置 注入ILogggerFactory,而後配置參數
//添加控制檯輸出 loggerFactory.AddConsole(Configuration.GetSection("Logging"));
       //添加調試輸出 loggerFactory.AddDebug(); app.UseMvc(); } }

 這種結構就比較清晰明瞭。

四、Logging源碼解析

  三種配置其實都是爲了注入日誌相關的服務,可是調用的方法稍有不一樣。如今咱們以第二種配置來詳細看看其注入過程。首先調用AddLogging方法,其實現源碼以下:
 public static IServiceCollection AddLogging(this IServiceCollection services, Action<ILoggingBuilder> configure)
        {
            services.AddOptions();//這裏會注入最基礎的5個服務 option相關服務只要是跟配置文件相關,經過Option服務獲取相關配置文件參數參數 

            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;
        }

接着會調用AddConfiguration

  public static ILoggingBuilder AddConfiguration(this ILoggingBuilder builder, IConfiguration configuration)
        {
            builder.AddConfiguration();
       //下面爲AddConfiguration的實現

        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;
        }

 下面來看打印日誌的具體實現: 

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爲LoggerInformation數組,若是你在Startup中添加了Console、Deubg日誌功能了,那loggers數組值有2個,就是它倆。
foreach (var loggerInfo in loggers) {  //循環遍歷每一種日誌打印,若是知足些日子的條件,才執行打印log方法。好比某一個日誌等級爲Info,
          //可是Console配置的最低打印等級爲Warning,Debug配置的最低打印等級爲Debug
          //則Console中不會打印,Debug中會被打印
if (!loggerInfo.IsEnabled(logLevel)) { continue; } try {
            
//每一種類型的日誌,對應的打印方法不一樣。執行對應的打印方法 loggerInfo.Logger.Log(logLevel, eventId, state, exception, formatter); } catch (Exception ex) { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(ex); } }     }

下面具體看一下Console的打印實現:

首先ConsoleLogger實現了ILogger的Log方法,並在方法中調用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);
                //這裏是主要的代碼實現,能夠看到,並無寫日誌的代碼,而是將日誌打入到一個BlockingCollection<LogMessageEntry>隊列中
         //這裏須要指出 BlockingCollection是線程安全的集合,多個線程同時訪問,不會發生數據混亂。
_queueProcessor.EnqueueMessage(new LogMessageEntry() { Message = logBuilder.ToString(), MessageColor = DefaultConsoleColor, LevelString = hasLevel ? logLevelString : null, LevelBackground = hasLevel ? logLevelColors.Background : null, LevelForeground = hasLevel ? logLevelColors.Foreground : null }); }
       ...... }
 下面看日誌被放入隊列後的具體實現: 
 
 

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() { //在構造函數中啓動一個線程,執行ProcessLogQueue方法
       //從下面ProcessLogQueue方法能夠看出,是循環遍歷集合,將集合中的數據打印
_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()方法比較特殊,當集合中沒有值時,會阻塞本身,一但有值了,直到集合中又有元素繼續遍歷
          foreach (var message in _messageQueue.GetConsumingEnumerable()) { WriteMessage(message); } } catch { try { _messageQueue.CompleteAdding(); } catch { } } }   }
相關文章
相關標籤/搜索