Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Logger.IsEnable when used with LoggerMessage can lead to inconsistent behavior #36703

@paulomorgado

Description

@paulomorgado

The last code sample advises to use _logger.IsEnabled(LogLevel.Information) to avoid costly computations when logging is not enabled for the desired level.

The issue here is that now there are, at least, 2 places where the logging level needs to be coded.

A better advice would be to add an XXXIsEnabled method to the LogMessages class:

using Microsoft.Extensions.Logging;

namespace Logging.LibraryAuthors;

internal static partial class LogMessages
{
    [LoggerMessage(
        Message = "Sold {quantity} of {description}",
        Level = LogLevel.Information,
        SkipEnabledCheck = true)]
    internal static partial void LogProductSaleDetails(
        this ILogger logger,
        int quantity,
        string description);

    internal static bool IsLogProductSaleDetailsEnabled(
        this ILogger logger) => logger.IsEnabled(LogLevel.Information);
}

Better yet would be for the code generator to generate that method.


Document Details

Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions