只有累積,沒有奇蹟

2019年3月7日 星期四

[.NETCore] ASP.NET Core - Logging 日誌初體驗 (一)

前言
在前一篇的文章裡介紹 ASP.Net Core 中如使用 NLog 將日誌紀錄於指定的位置檔案中,在ASP.Net Core 內建 logging framework ,專門負責記錄 log 與提供 API 與第三方紀錄套件像是 NLog、Log4Net 整合搭配使用,這篇文章是閱讀 MSDN 官網的 ASP.NET Core logging 後摘錄重點筆記,若有問題歡迎提出一起討論或是給予指導

使用 ILogger
首先新增一個 .Net Core API 專案測試 Logging Framework,在 .NET Core 中到處充滿著 DI (Dependency Injection) 的設計,DI 要使用的第一步是要先註冊,因此在專案一起來時 Startup.cs 類別中的 configureServices 中注入日誌,且透過 AddConsole() 方法將所要輸出的日誌內容輸出至 Visual Studio 視窗中。在 configureServices 區段新增下列代碼
services.AddLogging(builder =>
{
    builder.AddConfiguration(Configuration.GetSection("Logging"))
        .AddConsole()
        .AddDebug();
});
接著在開啟範例專案的 ValueController 類別,在 ValuesController 新增參數為 ILogger 的建構子方法,並在方法中指定區域變數 _logger 為建構子指定的 logger,並於 public get 方法使用 loginformation 方法紀錄進來的參數值與 logWarning 方法紀錄異常時的資訊
private ILogger _logger; 
public ValuesController(ILogger<ValuesController> logger)
{
    _logger = logger;
}

// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
    _logger.LogInformation("輸入的參數 id : {id}", id);
    if (id == 0)
    {
        _logger.LogWarning("參數 id 為 0, 方法不支援也找不到資料唷");
    }

    return "value";
}
完成後建置專案並進行測試,啟動專案並在網址輸入  https://localhost/api/values/9487  和  https://localhost/api/values/0  測試該 API 接口 Log 狀況,輸出訊息資訊一開始是指定 AddConsole() 所以可以再 Visual Studio 的 output windows 輸出內容如下
可以看到 Log 的內容大部分為 .NET Core Lifecycle 進行時所記錄的日誌,紅色框的部分則是稍早測試希望記錄的日誌訊息,輸入的參數為 xx 都有被正確的記錄下來,從以上可以知道在 .NET Core 中內建的 logging Framework 使用上並不困難,且在此案例中並未使用到其他 logging 框架也可將資訊正確的輸出,

使用 ILoggerFactory
使用 ILogger 輸出時預設記錄日誌類別名稱,已 Demo專案為例 namespace 為 NETCoreLogging.Controllers,類別命名為 ValueController 因此日誌看到的完整訊息為下
NETCoreLogging.Controllers.ValueController:your log balabalalalalaala
如果希望用不同的方式來命名的話,則可以使用 ILoggerFactory.CreateLogger 來達到自訂的需求,ILogger 與 ILoggerFactory 兩個介面都是  Microsoft.Extensions.Logging  命名空間底下取得,使用方式如下
public ILogger _logger; 
public ValuesController(ILoggerFactory logger)
{
    _logger = logger.CreateLogger("MyDemoProject");
}
將建構子注入的 ILogger 改為 ILoggerFactory 介面,接著在使用 ILoggerFactory.CreateLogger 方法來自訂名稱 MyDemoProject ,日誌輸出顯示如下
MyDemoProject:Information: 輸入的參數 id : 9527
兩種方式在使用上都不難,端看團隊需求而定是走預設  ILogger  或是想自訂日誌格式  ILoggerFactory 

篩選紀錄
上面介紹了如何使用 .NET Core 內建的 logging Framework 輸出日誌,在輸出的日誌中看到了很多 Microsoft 或是 system 類的 log 資訊,這些資訊在過去是比較少看到的,假設今天希望在特定專案可以不要輸出這些底層或是日誌資訊,則可以透過 logging 中的篩選機制  AddFilter 來達到此目的,舉例來說將在 configureServices 區段加上 addFilter 設定篩選的條件
services.AddLogging(builder =>
{
    builder.AddConfiguration(Configuration.GetSection("Logging"))
        .AddFilter("Microsoft", LogLevel.Warning)        
        .AddConsole()
        .AddDebug(); 
}
原本的日誌內容就會從
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44301/api/values/7777  
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Get", controller = "Values"}. Executing action NETCoreLogging.Controllers.ValuesController.Get (NETCoreLogging)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method NETCoreLogging.Controllers.ValuesController.Get (NETCoreLogging) with arguments (7777) - Validation state: Valid
MyDemoProject:Information: 輸入的參數 id : 7777
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action method NETCoreLogging.Controllers.ValuesController.Get (NETCoreLogging), returned result Microsoft.AspNetCore.Mvc.ObjectResult in 4.4479ms.
Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor:Information: Executing ObjectResult, writing value of type 'System.String'.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action NETCoreLogging.Controllers.ValuesController.Get (NETCoreLogging) in 67.7888ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 82.4591ms 200 text/plain; charset=utf-8
改為
MyDemoProject:Information: 輸入的參數 id : 7777
塞選過後精簡許多,過濾掉許多不需要的資訊留下真正重要的內容,如果想了解更多關於 logging 篩選的規則也可以參考 MSDN 官方說明 : 傳送門 

後記
這篇簡單說到在.NET Core 如何使用 ILogger 與 ILoggerFactory 紀錄 Log 的方式,以及如何篩選需要的 log 方法,原本想在介紹 appsettings.json 與 Log level 差異但想一想還是拆成兩篇來詳細說明比較適合,在之後的時間可以在整理出來讓大家更容易了解,也希望自己可以有時間不要像是獵人一樣拖稿 XDD

參考
ASP.NET Core 中的記錄



0 意見:

張貼留言

Copyright © m@rcus 學習筆記 | Powered by Blogger

Design by Anders Noren | Blogger Theme by NewBloggerThemes.com