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


1、介紹

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

2、默認配置

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

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

 運行結果如下:

 

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

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中讀取配置。

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

 3、建立自己的Logging配置

  首先修改Program類

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();

        //第二種配置 也可以這樣加上日志功能,不用下面的注入
        //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,然后配置參數
//添加控制台輸出 loggerFactory.AddConsole(Configuration.GetSection("Logging"));
       //添加調試輸出 loggerFactory.AddDebug(); app.UseMvc(); } }

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

4、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 { } } }   }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM