Excellent LoggerMessage Performance in Microsoft.Extensions. Logging in

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.
public static class LoggerMessageTemplates
{
    // A reusable logging delegate for informational logs
    private static readonly Action<ILogger, int, Exception> _logInfo =
        LoggerMessage.Define<int>(
            LogLevel.Information,
            new EventId(1, "LoggerMessageTemplates"),
            "Processing user from template: {UserId}");

    // Helper method for informational logs
    public static void LogInfo(this ILogger logger, int userId)
    {
        _logInfo(logger, userId, null!); // For info, pass null for the exception parameter
    }
}

Benchmark Code & Result

[Benchmark(Baseline = true)]

public Task ILogger()
{
	for (int userId = 1; userId <= 1000000; userId++)
	{
		_logger.LogInformation("Processing user {userId}", userId);
	}
	return Task.CompletedTask;
}
[Benchmark]
public Task LoggerMessage()
{
	for (int userId = 1; userId <= 1000000; userId++)
	{
		_logger.LogInfo(userId);
	}
	return Task.CompletedTask;
}

Best and Most Recommended ASP.NET Core 8.0.11 Hosting

Fortunately, there are a number of dependable and recommended web hosts available that can help you gain control of your website’s performance and improve your ASP.NET Core 8.0.11 web ranking. HostForLIFE.eu is highly recommended. In Europe, HostForLIFE.eu is the most popular option for first-time web hosts searching for an affordable plan.

Their standard price begins at only €3.49 per month. Customers are permitted to choose quarterly and annual plans based on their preferences. HostForLIFE.eu guarantees “No Hidden Fees” and an industry-leading ’30 Days Cash Back’ policy. Customers who terminate their service within the first thirty days are eligible for a full refund.

By providing reseller hosting accounts, HostForLIFE.eu also gives its consumers the chance to generate income. You can purchase their reseller hosting account, host an unlimited number of websites on it, and even sell some of your hosting space to others. This is one of the most effective methods for making money online. They will take care of all your customers’ hosting needs, so you do not need to fret about hosting-related matters.