C
C#3mo ago
Mango

Warning CA1848 : For improved performance, use the LoggerMessage delegates...

Can someone show me how implement LoggerMessage into here? My brain is not connecting the dots:
public class ExceptionFilterMiddleware
{
private readonly ILogger<ExceptionFilterMiddleware> _logger;
private readonly RequestDelegate _next;

public ExceptionFilterMiddleware(ILogger<ExceptionFilterMiddleware> logger, RequestDelegate next)
{
_logger = logger;
_next = next;
}

public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError("An exception occurred processing the request: {ex}", ex); <-- rule violation here
context.Response.ContentType = MediaTypeNames.Application.Json;
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

var json = JsonSerializer.Serialize(new { Message = ex.Message }, context.RequestServices.GetRequiredService<JsonSerializerOptions>());
await context.Response.WriteAsync(json);
}
}
}
public class ExceptionFilterMiddleware
{
private readonly ILogger<ExceptionFilterMiddleware> _logger;
private readonly RequestDelegate _next;

public ExceptionFilterMiddleware(ILogger<ExceptionFilterMiddleware> logger, RequestDelegate next)
{
_logger = logger;
_next = next;
}

public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError("An exception occurred processing the request: {ex}", ex); <-- rule violation here
context.Response.ContentType = MediaTypeNames.Application.Json;
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

var json = JsonSerializer.Serialize(new { Message = ex.Message }, context.RequestServices.GetRequiredService<JsonSerializerOptions>());
await context.Response.WriteAsync(json);
}
}
}
12 Replies
lycian
lycian3mo ago
This SO kind of explains it https://stackoverflow.com/questions/75893617/loggermessage-structured-logging Basically you're paying an up front cost once to parse the template.
Stack Overflow
LoggerMessage structured logging
I'm using LoggerMessage logging in my application. I want to use structured logging like below. But I don't see a way. Is this possible in LoggerMessage ? logger.LogInformation("Test {id}"...
lycian
lycian3mo ago
There's also caveats, because improvements have been made in this area with https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/interpolated-string-handler So if you're using a newer logging library hopefully it has interpolated string handlers and you can just use those
Explore string interpolation handlers - C#
This advanced tutorial shows how you can write a custom string interpolation handler that hooks into the runtime processing of an interpolated string.
Mango
Mango3mo ago
So it sounds like you don’t have to implement that if you don’t want to
lycian
lycian3mo ago
nope, up to the logging library. LoggerMessage will always keep the efficiency It's more verbose though
Mango
Mango3mo ago
Looks like you lose the string interpolation though
lycian
lycian3mo ago
"An exception occurred processing the request: {ex}" is a formatted string $"An exception occurred processing the request: {ex}" would be the string interpolation form of that
Mango
Mango3mo ago
I meant the ability to pass in the argument as values too Maybe I’m using the wrong overload for Error I want to log an error with a preamble and the exception itself
lycian
lycian3mo ago
not really, I think LoggerMessage is a little bit harder to understand. The attribute form is a bit easier to think about because it just becomes a method call
lycian
lycian3mo ago
Compile-time logging source generation - .NET
Learn how to use the LoggerMessageAttribute and compile-time source generation for logging in .NET.
lycian
lycian3mo ago
but at the end of the day, it's a perf problem. If you're not in a tight loop and the extra string allocation isn't a problem then just don't worry about it 🙂
Mango
Mango3mo ago
Yeah it’s in a part of a code I would hope doesn’t ever get called If it does it would be as little as possible I’m not logging in an iteration I’ll mute that warning and file it under “things to try later” So what’s a good use case for high performance logging? Operations where logging is the primary IO? Which seems odd
lycian
lycian3mo ago
any logging in a tight loop