前面透過幾篇文章介紹了關於 Serilog 在 ASP.NET Core 中的應用,分別是
分析
Exception Usage
當記錄 Log 是應用在例外情境時,會檢查是否有傳遞 exception 參數,而不是定義在屬性中
以上代碼會提示 The exception 'ex' should be passed as first argument,如下圖所示
- try
- {
- // to do something
- }
- catch (Exception ex)
- {
- Log.Error("Could not save {File}: {Error}", file, ex);
- throw;
- }
因此正確的記錄方式應該是以下代碼
- catch (Exception ex)
- {
- Log.Error(ex, "Could not save {File}", file);
- }
Property Binding Verifier
檢查紀錄 Log 時的 property 是否有遺漏,舉例來說下列代碼要紀錄 file 與 driectory ,少傳入一個參數在紀錄時會發生錯誤
筆記 : 使用 Serilog Analyzer 前後比較,未安裝前是不會提示錯誤的唷
- Log.Information("Saving {File} to {Directory}", file);
Message Template Syntax Verifier
Message Template 檢查也就是會確認你的格式是否正確,如果違反 message template 會提示錯誤,以下為格式錯誤範例(少一個 { )
提示如下
- Log.Information("Saving {File to {Directory}", file, directory);
正確如下
- Log.Information("Saving {File} to {Directory}", file, directory);
Configuration
分析 Serilog logging 配置生成對應的 <appSettings> 或是 appSettings.json,不囉嗦直接看官方範例
後記
以上簡單僅介紹幾種使用的情境,官方支援更多的檢查與驗證,如果有興趣了解更多可以參考官方網站,另外有在網路上看到使用時會與 Resharper 衝突,但自己在使用時並未遇到衝突而不能使用的情境,如果有遇到也可以留言一起討論解決方案 :)
參考
SerilogAnalyzer
0 意見:
張貼留言