S4487 FP with source generators

I am seeing false positives reported in SonarCloud under the rule csharpsquid:S4487 using automatic analysis for the following .NET 8/C# 12 code:

public partial class LambdaEntryPoint : ILambdaEntryPoint
    private readonly ILogger<LambdaEntryPoint> _logger;

    public LambdaEntryPoint(ILogger<LambdaEntryPoint> logger)
        _logger = logger;

    public async Task<SQSBatchResponse> Handle(SQSEvent sqsEvent, ILambdaContext context)
        var failures = new List<SQSBatchResponse.BatchItemFailure>();
        var serialiser = new SourceGeneratorLambdaJsonSerializer<SqsSerializerContext>();
        foreach (var message in sqsEvent.Records)
            // further processing goes here
        return new SQSBatchResponse(failures);

    [LoggerMessage(Level = LogLevel.Information, Message = "Processing message {MessageId}")]
    public partial void LogProcessingMessage(string messageId);

I am seeing the following error : Remove this unread private field '_logger' or refactor the code to use its value.. However, the field is being used behind the scenes by the source generator that writes out the optimised logging code for my function.

Hey @davidkeaveny!

This smells a bit like this issue, can you have a look?

Hi Colin, it does seem to be slightly similar - there’s some source generation going on that code analysis isn’t aware of. However, my example is happening in SonarCloud’s automatic analysis, rather than client-side within Rider (as it happens, I do use Rider, but I’ve turned off SonarLint), so I don’t think the solution will be the same.

Thanks. I’ll flag this for some expert eyes.

1 Like

Hello @davidkeaveny,

the automatic analysis for .Net does not support source generators. Therefore, the compile-time logging source generation isn’t executed.
This leads to the false positive you reported. This is a known limitation of automatic analysis for .NET projects and will be fixed in the future.

Best regards,

Just to extend @Martin_Strecker’s answer, you can avoid the false-positives for now by switching to CI-based analysis.

1 Like

Many thanks @Martin_Strecker , I look forward to seeing it addressed in the future.

Actually we’re switching from CI-based analysis to automatic analysis, because with 5-6 applications in our monorepo and a relatively brisk rate of development for a greenfield project approaching MVP, we were burning through GitHub Actions minutes at a shocking rate and were in danger of being capped/rate limited, which would have a big impact on the rest of our organisation!

Switching from Windows runners to Ubuntu reduced the execution time by about 40%, but with more projects coming online and starting to use SonarCloud, it’s not sustainable for us to use CI-based analysis in this project at least (and we’re one of the first to use source generators).