Skip to content

What is the recommended way of using the ILogger in Minimal APIs? #49882

Closed Answered by martincostello
KennethHoff asked this question in Q&A
Discussion options

You must be logged in to vote

One way of achieving this is to use the app.Logger property captured into the closure of your handler method. In this case the logger source will just be the name of your app.

app.MapGet("/greet", () =>
{
    app.Logger.LogDebug("Returning greeting");
    return "Hello";
});

This is simple, but has the disadvantage of capturing state via the closure, but also means all of your logging has the same source name.

You could also manually register ILogger yourself and give it a custom name at the time of construction:

builder.Services.AddTransient<ILogger>(p =>
{
    var loggerFactory = p.GetRequiredService<ILoggerFactory>();
    // You could also use the HttpContext to make the name dynamic f…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@grrttedwards
Comment options

@martincostello
Comment options

Answer selected by KennethHoff
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc
4 participants