It eliminates the need to tinker with string manipulation at runtime by using strongly-typed delegates to log messages. It’s similar to having a ready-to-use log template that has already been baked.
A Simple Comparison with Benchmark
I tested two ways to log 1M user IDs.
- ILogger extension methods: Most of us are used to this. It formats the log message at runtime, which can be slow and memory-heavy.
- LoggerMessage: This pre-compiles the log template, so it’s lightning-fast and super lightweight.
Why Is It So Fast?
- ILogger extension methods: Every time you log, it has to parse the template, format the string, and allocate memory for the result. This happens every single time you log something.
- LoggerMessage: The log template is pre-compiled, so there’s no runtime string formatting.
It uses a reusable Action, so it just plugs in the values and logs the message. While there’s still a small amount of work to insert the values, it’s drastically faster than full string formatting. No extra work, no extra memory.
Some Pitfalls and Considerations
- Not Always Necessary: For simple, infrequent logging, the performance gains of LoggerMessage might not be noticeable.
- Context: LoggerMessage primarily focuses on the formatting aspect. It doesn’t inherently provide richer contextual information..We’ll still need to handle things like log levels, event IDs, and structured logging separately.
Benchmark Code & Result