Skip to content

LoggerMessageGenerator emits malformed strings. #123786

@John-Leitch

Description

@John-Leitch

Description

The LoggerMessageGenerator class does not properly handle escaping, sometimes emitting malformed strings that do not compile.

Reproduction Steps

The following program demonstrates the issue:

using Microsoft.Extensions.Logging;

namespace LoggerMessageEscapeRepro;

public static partial class LoggerMessageTest
{
    [LoggerMessage(
        EventId = 1,
        Level = LogLevel.Information,
        Message = "Foo \\ bar: {foo}")]
    static partial void Test(ILogger logger, string foo);
}

internal class Program
{
    static void Main(string[] args)
    {
        var logger = new LoggerFactory().CreateLogger<Program>();
        Console.WriteLine("Hello, World!");
    }
}

Expected behavior

The following field is expected in the generated source:

[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Logging.Generators", "10.0.13.7005")]
private static readonly global::System.Action<global::Microsoft.Extensions.Logging.ILogger, global::System.String, global::System.Exception?> __TestCallback =
    global::Microsoft.Extensions.Logging.LoggerMessage.Define<global::System.String>(global::Microsoft.Extensions.Logging.LogLevel.Information, new global::Microsoft.Extensions.Logging.EventId(1, nameof(Test)), "Foo \\ bar: {foo}", new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 

Actual behavior

The following field is what is actually emitted (note the invalid escape sequence):

[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Logging.Generators", "10.0.13.7005")]
private static readonly global::System.Action<global::Microsoft.Extensions.Logging.ILogger, global::System.String, global::System.Exception?> __TestCallback =
    global::Microsoft.Extensions.Logging.LoggerMessage.Define<global::System.String>(global::Microsoft.Extensions.Logging.LogLevel.Information, new global::Microsoft.Extensions.Logging.EventId(1, nameof(Test)), "Foo \ bar: {foo}", new global::Microsoft.Extensions.Logging.LogDefineOptions() { SkipEnabledCheck = true }); 

Regression?

No response

Known Workarounds

Double escaping works in at least some cases, but this is not an acceptable solution.

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions