Tuesday, January 4, 2022

Using ILogger in minimal .Net ASP.Net Core API Application

.Net 6.0 introduced the minimal API model for WebAPIs. That is highly reducing the amount of boilerplate code to be used to run WebAPIs. All actions can be included in a single file. This post is not to explain the wow factor of the Minimal API model but to give some tips to use ILogger in minimal APIs.

Using ILogger outside of action method

This is about using the ILogger in the Program.cs


ILoggerFactory loggerFactory = app.Services.GetRequiredService<ILoggerFactory>();
ILogger logger=loggerFactory.CreateLogger("MinimalAPI");

Once we get the ILogger object, we can use its methods to log. This can be directly used in Program.cs without any class.

Using ILogger inside the action method

Inside the action method, we can get the ILoggerFactory object and obtain the ILogger using the factory. 
app.MapGet("/api/circle/areaOf/{radius}", async (int radius,Calculator calc, ILoggerFactory loggerFactory) =>
{
    ILogger localLogger = loggerFactory.CreateLogger("CircleAPI");
    localLogger.LogTrace($"api/circle/areaOf/{radius} - Started.");
    return await calc.AreaOfCircle(radius);
}).WithName("AreaOfCircle");

The only difference is that we don't get the generic version of ILogger<T>. Hope not many extra details are required to use this tip.

Sample

Please download from GitHub.

Happy logging. 

No comments: