Skip to content

LoggerMessage source generator does not work with logger from primary constructor. #91121

@stmimon

Description

@stmimon

Description

The source generator for LoggerMessage does not work if the logger is injected from the primary constructor.

Reproduction Steps

Create the project.

  • dotnet new classlib
  • dotnet add package Microsoft.Extensions.Logging --version 8.0.0-preview.7.23375.6

Add the following c# file to the project.

using Microsoft.Extensions.Logging;

namespace Test;

public partial class LoggerFromPrimaryConstructor(ILogger<LoggerFromPrimaryConstructor> logger)
{
    [LoggerMessage(Level = LogLevel.Debug, Message = "This is a test")]
    public partial void LogTest();
}

Expected behavior

The source generator emits code with similar behaviour as if I had written the following.

public partial class LogWithExplicitProperty
{
    private readonly ILogger<LoggerFromPrimaryConstructor> logger;

    public LogWithExplicitProperty(ILogger<LoggerFromPrimaryConstructor> logger)
    {
        this.logger = logger;
    }

    [LoggerMessage(Level = LogLevel.Debug, Message = "This is a test")]
    public partial void LogTest();
}

Actual behavior

Compilation fails with error SYSLIB1019: Couldn't find a field of type Microsoft.Extensions.Logging.ILogger in class LoggerFromPrimaryConstructor.

I also got error CS1525: Invalid expression term '<' in another project where the source generator did find the logger for some reason, but generated incorrect code that referenced the logger by the symbol <logger>P. I assume this is the generated field name? I could not reproduce it however.

Regression?

This is not a regression, as primary constructors are not GA.

Known Workarounds

Use a regular constructor instead of a primary constructor.

Configuration

I am using .NET 8 preview 7 on Windows 10 Enterprise 22H2 x64.

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Extensions-Loggingin-prThere is an active PR which will close this issue when it is merged

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions