SerilogAnalyzer icon indicating copy to clipboard operation
SerilogAnalyzer copied to clipboard

Allow namespaces to be changed to support use cases with wrapper classes

Open brianfeucht opened this issue 4 years ago • 3 comments

We use wrappers around Serilog in our implementation. This means this analyzer didn't work for us since it was looking for specific namespaces. By allowing these namespaces to be updated we can utilize this analyzer without any additional code changes.

brianfeucht avatar Dec 16 '20 23:12 brianfeucht

@brianfeucht Trying to understand, How can we now tell the analyser that our new wrapper method exist in a namespace?

JinsPeter avatar Dec 03 '24 09:12 JinsPeter

@Suchiman Would you please consider merging this if this can make a difference?

JinsPeter avatar Dec 03 '24 09:12 JinsPeter

@JinsPeter

Here is what we have done (via forked code):

Create an implementation of StructuredLoggerAnalyzer with the following overridden:

  • ILogger with the implementation type you'd like to analyze
  • LoggerMethodAttribute with a new attribute type

We then decorate our implementation type with the new attribute.

    [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method)]
    public sealed class MessageTemplateFormatMethodAttribute : Attribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageTemplateFormatMethodAttribute"/> class.
        /// </summary>
        /// <param name="messageTemplateParameterName">Name of the message template parameter.</param>
        public MessageTemplateFormatMethodAttribute(string messageTemplateParameterName)
        {
            MessageTemplateParameterName = messageTemplateParameterName;
        }

        /// <summary>
        /// Gets the name of the message template parameter.
        /// </summary>
        /// <value>The name of the message template parameter.</value>
        public string MessageTemplateParameterName { get; private set; }
    }
    
    public interface IStructuredLogger 
    { 
        [MessageTemplateFormatMethod("messageTemplate")] void Debug(Exception exception, string messageTemplate, params object[] propertyValues);
        [MessageTemplateFormatMethod("messageTemplate")] void Debug(string messageTemplate, params object[] propertyValues);
    }
    
    public StructuredLoggerAnalyzer : DiagnosticAnalyzer {
        protected virtual string ILogger => "IStructuredLogger ";
        protected virtual string LoggerMethodAttribute => "MessageTemplateFormatMethodAttribute";
    }

When then build and package up this project as our own analyzer and import it into our project.

brianfeucht avatar Dec 03 '24 15:12 brianfeucht