Skip to content

Instantly share code, notes, and snippets.

@robfe
Created October 4, 2018 22:58
Show Gist options
  • Save robfe/f54eb546d97390fdf8fc71dfc27d34cf to your computer and use it in GitHub Desktop.
Save robfe/f54eb546d97390fdf8fc71dfc27d34cf to your computer and use it in GitHub Desktop.
/// <summary>
/// Serilog won't be able to pull structured props out of a C# interpolated string.
/// See https://nblumhardt.com/2015/01/c-6-string-interpolation-and-serilog/
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NoInterpolationInSerilogAnalyzer : DiagnosticAnalyzer
{
const string Category = "Logging";
const string Title = "String interpolation breaks Serilog structuring";
const string MessageFormat = "String interpolation breaks Serilog structuring";
const string Description = "String interpolation breaks Serilog structuring. See https://nblumhardt.com/2015/01/c-6-string-interpolation-and-serilog/";
static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor("REPLACEME", Title, MessageFormat, Category, DiagnosticSeverity.Error, true, Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(analysisContext =>
{
var n = (InvocationExpressionSyntax)analysisContext.Node;
var firstInterpolatedString = n.ArgumentList.Arguments
.Select(x => x.Expression)
.OfType<InterpolatedStringExpressionSyntax>()
.FirstOrDefault();
if (firstInterpolatedString == null)
{
return;
}
if (n.Expression is MemberAccessExpressionSyntax ma)
{
//are we calling the method on something that belongs to Serilog?
var typeInfo = analysisContext.SemanticModel.GetTypeInfo(ma.Expression);
if (typeInfo.Type.ContainingNamespace.Name == "Serilog")
{
analysisContext.ReportDiagnostic(Diagnostic.Create(Rule, firstInterpolatedString.GetLocation()));
}
}
}, SyntaxKind.InvocationExpression);
}
}
@robfe
Copy link
Author

robfe commented Oct 4, 2018

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment