Serilog - Output/Enrich All Messages with MethodName from which log entry was Called

后端 未结 5 1750
面向向阳花
面向向阳花 2020-12-02 16:24

Is there anyway to enrich all Serilog output with the Method Name.

For Instance consider If I have the following;

Public Class MyClassName

  Privat         


        
5条回答
  •  [愿得一人]
    2020-12-02 16:41

    in case you need a version in C#:

    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 like this:

    // at the beginning of the class
    private static Serilog.ILogger Log => Serilog.Log.ForContext();
    
    // in the method
    Log.Here().Information("Hello, world!");
    

    Remember to add those properties in the message template. You can use something like this:

    var outputTemplate = "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message}{NewLine}in method {MemberName} at {FilePath}:{LineNumber}{NewLine}{Exception}{NewLine}";
    
    Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Warning()
                .Enrich.FromLogContext()
                .WriteTo.RollingFile("log/{Date}.log", outputTemplate, LogEventLevel.Warning)
                .WriteTo.Console(LogEventLevel.Warning, outputTemplate, theme: AnsiConsoleTheme.Literate)
                .CreateLogger();
    

提交回复
热议问题