Home > Blockchain >  Custom Compiler Warning To Remind To Use Method
Custom Compiler Warning To Remind To Use Method

Time:08-07

I have written an extension method on ILogger and need the complier to emit warning to use that extension method whenever someone use an ILogger instance. For example:

Extension method on ILogger

public static class LoggerExtensions
{
    public static ILogger Here(this ILogger logger,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string sourceFilePath = "",
        [CallerLineNumber] int sourceLineNumber = 0) {
        return logger
            .ForContext("MemberName", memberName)
            .ForContext("FilePath", sourceFilePath)
            .ForContext("LineNumber", sourceLineNumber);
    }
}

Use ILogger instance will emit warning

// at the beginning of the class
private static Serilog.ILogger Log => Serilog.Log.ForContext<MyClass>();

// in the method

Log.Information("Warning: need to use Here() on ILogger") // the compiler emits warning to use Here()
Log.Here().Information("No warning here."); // this is good. No warning

Any help is much appreciated!

CodePudding user response:

Here are some ideas:

  1. Don't do it. Logs should identify themselves by the message/eventid. You don't need to know the line numbers - these can change over time anyway.
  2. Setup your DI to return a logger that does the extra logging.
  3. Setup the context in the constructor (this will not give you line numbers, but you can capture other info)
  4. Write an analyzer. The official tutorial is Tutorial: Write your first analyzer and code fix.
  5. Write a script that scans for what you need and run it from time to time. You can even make this a test.
  •  Tags:  
  • c#
  • Related