Serilog 日志使用(一) .net core .net5.0


Serilog可以很好的對.net core 進行內置日志集成處理

其基本配置可以通過外部讀取,也可以內部通過代碼判斷
可以使用:

  Serilog.Settings.AppSettings

  Serilog.Settings.Configuration

Serilog.Sinks.Console 將日志讀取到控制台
Serilog.Sinks.File 將日志讀取到文件

Serilog.Sinks.MariaDB 將日志寫入數據庫需要用到(支持sqlserver ,Mysql) 其它數據庫需要安裝相應的nuget包,具體可以查閱官方文檔

當然還有許多好用的Nuget包

同時支持多種關系型數據庫和非關系型數據庫

 

 

 

基本配置
WriteTo 用於設置日志接受器,可以單個也可以多個
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("log-.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();

outputTemplate 輸出日志模板設置

.WriteTo.File("log.txt",
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")


設置日志輸出的最小粒度等級
.MinimumLevel.Debug()
輸出的日志等級可以設置全局,也可以單獨設置
如下為單獨控制面板的日志等級
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)


對內置日志輸出粒度的重寫
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)

 


json文件內容示例
"Serilog": {
"Using": [
"Serilog.Sinks.MariaDB"
],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "MariaDB",
"Args": {
"connectionString": "server=localhost;Database=data;Uid=root;Pwd=123456;Port=3306;Allow User Variables=True;",
"autoCreateTable": true,
"tableName": "Logs",
"restrictedToMinimumLevel": "Information",
"batchPostingLimit": 1000, //批量寫入限制
"period": "0.00:00:30",
"options": {
"PropertiesToColumnsMapping": {
"Exception": "Exception",
"Timestamp": "Timestamp",
"Level": "Level",
"Message": "Message",
"MessageTemplate": "MessageTemplate",
"Properties": "Properties"
},
//"HashMessageTemplate": true, //是true(默認是false)時,使用 SHA256 算法對消息模板進行哈希處理。當您想通過消息模板搜索日志時,這可能會更方便。
"TimestampInUtc": false, //時間戳轉化
"ExcludePropertiesWithDedicatedColumn": true, //是true(默認為false)時,具有專用列的自定義屬性不包含在Properties列中。
"EnumsAsInts": false, //是true(默認為false)時,枚舉在保存之前被轉換為其對應的整數值,否則枚舉被存儲為字符串。
"LogRecordsCleanupFrequency": "0.02:00:00", //日志清理頻率
"LogRecordsExpiration": "31.00:00:00" //日志記錄過期設置 ,定期刪除處理
}
}
},
{
"Name": "Console"
}
]
}

 多看看官方文檔

 

感覺特別好的參考資料:
https://github.com/serilog/serilog-aspnetcore
https://serilog.net/
https://nblumhardt.com/
https://github.com/TeleSoftas/serilog-sinks-mariadb

 


免責聲明!

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



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