一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - ASP.NET教程 - 詳解.Net Core中的日志組件(Logging)

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

2020-05-31 14:14MicroHeart! ASP.NET教程

這篇文章主要介紹了詳解.Net Core中的日志組件(Logging),小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

1、介紹

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

2、默認配置

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[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" };
  }
}

運行結果如下:

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

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

?
1
2
3
4
5
6
7
8
9
10
11
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中讀取配置。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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方法,其實現源碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
   }

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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>隊列中
        _queueProcessor.EnqueueMessage(new LogMessageEntry()
        {
          Message = logBuilder.ToString(),
          MessageColor = DefaultConsoleColor,
          LevelString = hasLevel ? logLevelString : null,
          LevelBackground = hasLevel ? logLevelColors.Background : null,
          LevelForeground = hasLevel ? logLevelColors.Foreground : null
        });
      }
       ......
    }

下面看日志被放入隊列后的具體實現:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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 { }
      }
    }
  }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:http://www.cnblogs.com/MicroHeart/p/9341286.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 超碰av| 欧美一级特黄特色大片 | 日本精品一二三区 | 午夜私人福利影院 | 亚洲va欧美va国产va天堂影 | 色老大在线 | 日韩一本在线 | 艾秋麻豆果冻剧传媒在线播放 | 国产精品视频免费看 | 男女精品视频 | 美女视频黄a | 久久re热在线视频精6 | 久草在线福利视频在线播放 | 国产经典一区二区三区蜜芽 | 亚洲国产剧情中文视频在线 | 国产成人激情 | 日剧整部剧护妻狂魔免费观看全集 | 国产一区二区三区在线观看视频 | 亚洲精品123区在线观看 | 清纯漂亮女友初尝性过程 | 亚洲成av人片天堂网 | bl双性肉文 | 校花的第一次好紧好爽 | 色多多视频网站 | 秘书在办公室疯狂被hd | 亚洲国产日韩欧美一区二区三区 | 国产精品视频一区二区三区经 | 天天乐影院| 奶茶视频有容乃大 | 三级黄色片在线观看 | 99pao在线视频精品免费 | darkside动漫在线观看 | 范冰冰好紧好滑好湿 | tube69中国露脸 | 91av免费| oneday日本在线观看完整版 | 亚洲精品二三区伊人久久 | 日本中文字幕一区二区有码在线 | 国产做a爰片久久毛片 | 日本九九热 | 亚洲2卡三卡4卡5卡精品 |