使用Serilog來實現日志記錄
先安裝Serilog六件套神裝包:
也可以對個別相應的包進行刪除等,都是可以的。例如,標注的1是讀取配置文件的,如果不需要通過配置文件進行操作,就可以使用這個包。2是打印到控制台的,如果不需要打印到控制台,也可以不引用。3是寫入到文件的,如果不需要寫入到文件,也是可以不提供的。我在此處全部引入,方便可以使用多種日志記錄方法。Async是異步寫入日志,一般需要引入。
我們先在啟動項目的Program類里面,新增一些對Serilog的支持操作:
然后,在控制器里面添加對Logger<T>的依賴注入,並寫一些不同日志等級的日志記錄功能:
然后啟動項目,並執行一下該api方法,查看到日志打印的結果:
由於默認消息記錄級別是Warn,所以debug消息類型就看不見了。
以及寫入文本的日志,由於設定輸出到本目錄,所以可以在解決方案里面直接看見:
接下來使用配置文件的方式進行日志操作:
本部分serilog配置文件代碼:

"Serilog": { "MinimumLevel": { "Default": "Debug", //最小日志記錄級別 "Override": { //系統日志最小記錄級別 "Default": "Warning", "System": "Warning", "Microsoft": "Warning" } }, "WriteTo": [ { "Name": "Console" }, //輸出到控制台 { "Name": "Async", //異步寫入日志 "Args": { "configure": [ { "Name": "File", //輸出文件 "Args": { "path": "log/log.txt", "outputTemplate": "{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Class:{SourceContext}{NewLine}Message:{Message}{NewLine}{Exception}", "rollingInterval": "3" //日志文件生成精度:1:年 2:月 3:日 4:小時 } } ] } } ] }
在Program里面,注釋掉原先的代碼,然后新增一條通過配置文件進行讀取的語句:
因為配置文件里面設置的最小默認等級是Debug,所以現在可以全部打印出來:
配置文件里面配置的rollingInterval值為3,代表每天生成;path代表根目錄,設置log/log.txt代表根目錄下的log文件夾,按照每天(日期)生成的log開頭的txt日志文件。所以我們可以看見在根目錄下產生了一個日志文件log20210530.txt:
以上,代表Serilog通過配置文件成功。其中,還可以通過配置文件+啟動項配置兩個打配合進行配置出更適合自己的日志記錄風格,此處不再贅述,歡迎自己嘗試。
另外,Serilog還可以實現seq可視化功能,不過seq是收費的,所以這邊不做演示。也可以通過ElasticSearch+Kibana進行開發,實現日志可視化和日志搜索引擎功能,該部分功能敬請期待,將來會有這部分教程放出,現在還沒到時候。
本篇有關源碼:
Program:

public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } /// <summary> /// Serilog日志模板 /// </summary> static string serilogDebug = System.Environment.CurrentDirectory + "\\Log\\Debug\\.log"; static string serilogInfo = System.Environment.CurrentDirectory + "\\Log\\Info\\.log"; static string serilogWarn = System.Environment.CurrentDirectory + "\\Log\\Warning\\.log"; static string serilogError = System.Environment.CurrentDirectory + "\\Log\\Error\\.log"; static string serilogFatal = System.Environment.CurrentDirectory + "\\Log\\Fatal\\.log"; static string SerilogOutputTemplate = "{NewLine}時間:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}日志等級:{Level}{NewLine}所在類:{SourceContext}{NewLine}日志信息:{Message}{NewLine}{Exception}"; public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) // 添加Autofac .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>() .UseUrls("http://*:35678") .UseSerilog((context, logger) =>//注冊Serilog { logger.ReadFrom.Configuration(context.Configuration); logger.Enrich.FromLogContext(); //logger.WriteTo.Console(); // 輸出到Console控制台 //// 輸出到配置的文件日志目錄 //logger.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Debug).WriteTo.Async(a => a.File(serilogDebug, rollingInterval: RollingInterval.Hour, outputTemplate: SerilogOutputTemplate))) // .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Information).WriteTo.Async(a => a.File(serilogInfo, rollingInterval: RollingInterval.Hour, outputTemplate: SerilogOutputTemplate))) // .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning).WriteTo.Async(a => a.File(serilogWarn, rollingInterval: RollingInterval.Hour, outputTemplate: SerilogOutputTemplate))) // .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error).WriteTo.Async(a => a.File(serilogError, rollingInterval: RollingInterval.Hour, outputTemplate: SerilogOutputTemplate))) // .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Fatal).WriteTo.Async(a => a.File(serilogFatal, rollingInterval: RollingInterval.Hour, outputTemplate: SerilogOutputTemplate))); }); }); }
WSKController:

[Route("api/[controller]")] [ApiController] public class WSKController : ControllerBase { private readonly ITestAutofac _autofac; private readonly ILogger<WSKController> _logger; public WSKController(ITestAutofac autofac, ILogger<WSKController> logger) { _autofac = autofac; _logger = logger; } [HttpPost] public IActionResult HelloWorld() { // _autofac.Test(); _logger.LogInformation("Info Message……"); _logger.LogWarning("Warning Message……"); _logger.LogDebug("Debug Message……"); _logger.LogError("Error Message……"); return Ok(); } }
最后,如果本文章對君有用,歡迎點贊、評論和打賞~~
版權所有,轉載請注明出處:https://www.cnblogs.com/weskynet/p/14829299.html