ASP.NET Core 實際輸出日誌訊息 示範

在上一篇 ASP.NET Core 使用 Serilog 套件寫 log 教學 將主要紀錄 log 的套件設定好後,接下來就是要實際寫 log 了

先看程式碼:

using Microsoft.AspNetCore.Mvc;

[ApiController]
public class TestController : ControllerBase
{
    private readonly ILogger<TestController> _logger;

    public TestController(ILogger<TestController> logger)
    {
        _logger = logger;
    }

    [HttpGet("/test")]
    public IActionResult Test()
    {
        _logger.LogTrace("Trace");
        _logger.LogDebug("Debug");
        _logger.LogInformation("Information");
        _logger.LogWarning("Warning");
        _logger.LogError("Error");
        _logger.LogCritical("Critical");
        return Ok();
    }
}
    

在第 6 行宣告 logger,記得要在角括號中放上當前類別的名稱
在 8 ~ 11 行建構子中使用 DI (Dependency Injection)將上一篇寫好的 log 套件自動注入到當中,就可以直接使用 _logger 來輸出 log 了,預設有 6 個等級,等級由低到高分別是
  • Trace: 最詳細的資訊,可能包含機密資訊
  • Debug: 用於測試
  • Information: 一般流程中輸出的,一般寫最多的也是這個
  • Warning: 警告事件,但不會發生嚴重問題
  • Error: 無法處理的錯誤和異常
  • Critical: 最嚴重的問題
預設只會輸出 Information 和更高的層級,如果想要顯示更多的話可以參考上一篇修改,不過一般不會調低,因為還有系統的其他訊息也會一起顯示,通常會手動禁用系統訊息方便找尋自訂訊息。

另外如果不是使用 ILogger 而是使用 Logger 的話在 log 時會拋出下面的錯誤:
    
[23:18:20 ERR] An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.Logger`1[WebApplicationSerilogTest2.Controllers.TestController]' while attempting to activate 'WebApplicationSerilog
Test2.Controllers.TestController'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
   at lambda_method3(Closure , IServiceProvider , Object[] )
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

    


參考資料:
Microsoft.learn - Logging in .NET Core and ASP.NET Core

留言