Skip to content

Logging Source Generator fails to compile due to CS8795 error with file-scoped namespaces #57880

Closed
@martincostello

Description

@martincostello

Description

If a class used to provide the partial methods for the Logging Source Generator uses file-scoped namespaces, the project fails to compile with errors similar to the below.

Project\Logger.cs(11,36): error CS8795: Partial method 'Logger.Greeting(ILogger, string)' must have an implementation part because it has accessibility modifiers. [Project\Project.csproj]
Project\Microsoft.Extensions.Logging.Generators\Microsoft.Extensions.Logging.Generators.LoggerMessageGenerator\LoggerMessage.g.cs(11,36): error CS0759: No defining declaration found for implementing declaration of partial method 'Logger.Greeting(ILogger, string)' [Project\Project.csproj]

Minimal repro

Project.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0-rc.1.21420.7" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0-rc.1.21420.7" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0-rc.1.21420.7" />
  </ItemGroup>
</Project>

Program.cs

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MyLibrary;

using var serviceProvider = new ServiceCollection()
    .AddLogging(builder => builder.AddConsole())
    .BuildServiceProvider();

var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger("MyLogger");

Logger.Greeting(logger, "World");

Logger.cs

using Microsoft.Extensions.Logging;

namespace MyLibrary;

internal partial class Logger
{
    [LoggerMessage(EventId = 1, Level = LogLevel.Information, Message = "Hello {Name}!")]
    public static partial void Greeting(ILogger logger, string name);
}

Expected Output

Project> dotnet run
info: MyLogger[1]
      Hello World!

Configuration

.NET SDK 6.0.100-rc.1.21420.39
Microsoft.Extensions.Logging 6.0.0-rc.1.21420.7

Regression?

No.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions