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:
12 Replies
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}"...
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.
So it sounds like you don’t have to implement that if you don’t want to
nope, up to the logging library. LoggerMessage will always keep the efficiency
It's more verbose though
Looks like you lose the string interpolation though
"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 thatI 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
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
Compile-time logging source generation - .NET
Learn how to use the LoggerMessageAttribute and compile-time source generation for logging in .NET.
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 🙂
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
any logging in a tight loop