Skip to content

Debug logger does not print if the formatted message is empty, even if an exception is provided #116314

Closed
@colejohnson66

Description

@colejohnson66

Description

In the DebugLogger implementation, it does not log anything to the debug output if the formatted message is blank, even if an exception is provided.

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
ArgumentNullException.ThrowIfNull(formatter);
string message = formatter(state, exception);
if (string.IsNullOrEmpty(message))
{
return;
}
message = $"{logLevel}: {message}";
if (exception != null)
{
message += Environment.NewLine + Environment.NewLine + exception;
}
DebugWriteLine(message, _name);
}

Reproduction Steps

ILogger logger = new DebugLoggerProvider.CreateLogger("test");
new TestClass(logger).TestMethod();

public static partial class TestClass(ILogger logger)
{
    [LoggerMessage(LogLevel.Error)]
    private partial void LogException(Exception ex);

    public static void Method()
    {
        try
        {
            throw new InvalidOperationException("testing!");
        }
        catch (Exception ex)
        {
            LogException(ex);          // using source generator
            logger.LogError(ex, null); // "old"-style
        }
    }
}

Expected behavior

I see a debug output of the exception.

Actual behavior

Nothing is printed to the output because the message is empty.

Regression?

No response

Known Workarounds

Provide a dummy message to the source generator or "old"-style extension method:

[LoggerMessage(LogLevel.Error, "Exception.")]
private partial void LogException(Exception ex);

// --OR--

logger.LogError(ex, "Exception.");

Configuration

No response

Other information

The logger should only "fail" to write (i.e., do nothing) if neither a message nor an exception is provided.

Alternatively, if this is the desired behavior of ILogger, it should be made clear, possibly with an analyzer, that an exception with no message on LogError is a bad idea.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions