What is the recommended way of using the ILogger in Minimal APIs? #49882
-
Using Therefore, how do I inject the ILogger into my endpoint? The following throws a app.MapGet("/Greeting", (ILogger logger, string name) =>
{
logger.LogInformation("Does this work?");
return $"hello {name}";
}); What I have to do is something akin to this: // vvv What is T here?
app.MapGet("/Greeting", (ILogger<T> logger, string name) =>
{
logger.LogInformation("Does this work?");
return $"hello {name}";
}); I can only assume there is some other way to do this, but my Google-Fu is failing me today. I understand that |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
One way of achieving this is to use the 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 builder.Services.AddTransient<ILogger>(p =>
{
var loggerFactory = p.GetRequiredService<ILoggerFactory>();
// You could also use the HttpContext to make the name dynamic for example
return loggerFactory.CreateLogger("my logger");
}); If you want to use builder.Services.AddSingleton<MyService>();
var app = builder.Build();
app.MapGet("/stuff", async (MyService service) =>
await service.GetStuff());
class MyService
{
private _logger;
public MyService(ILogger<MyService> logger)
{
_logger = logger;
}
public Task<string> GetStuff()
{
_logger.LogDebug("Getting stuff");
return Task.FromResult("Hello");
}
} |
Beta Was this translation helpful? Give feedback.
-
You can also use For larger projects that use minimal APIs I use a CQRS based approach, endpoint just delegates to a handler and in that handler a typed logger can be injected via DI -- similar to the last approach shown in #49882 (comment) |
Beta Was this translation helpful? Give feedback.
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.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: