Created
October 4, 2018 22:58
-
-
Save robfe/f54eb546d97390fdf8fc71dfc27d34cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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); | |
} | |
} |
Author
robfe
commented
Oct 4, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment