vb.net - Serilog - 输出/丰富具有调用日志条目的 MethodName 的所有消息

标签 vb.net serilog

有没有办法用方法名称来丰富所有 Serilog 输出。

例如,考虑如果我有以下情况;

Public Class MyClassName

  Private Function MyFunctionName() As Boolean
      Logger.Information("Hello World")
      Return True
  End Function

End Class

所需的输出如下;

2015-04-06 18:41:35.361 +10:00 [Information] [MyFunctionName] Hello World!

实际上,完全限定名称会很好。

2015-04-06 18:41:35.361 +10:00 [Information] [MyClassName.MyFunctionName] Hello World!

“丰富器”似乎只适用于静态信息,并且不会每次都起作用。

最佳答案

如果您需要 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);
    }
}

像这样使用:

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

// in the method
Log.Here().Information("Hello, world!");

请记住在消息模板中添加这些属性。你可以使用这样的东西:

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();

关于vb.net - Serilog - 输出/丰富具有调用日志条目的 MethodName 的所有消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29470863/

相关文章:

.net - 是否可以从URL读取到System.IO.Stream对象?

c# - 如何使用 XML 树的可用结构在 C# 中构建 XML 树

asp.net-core-mvc - Serilog 附加属性

c# - XUnit 和 ITestOutputHelper 实例化

mysql - 如果选择 Combobox vb.net mysql,文本框中的数据库值

c# - 将 Excel 读取到数据表而不会丢失货币类型的精度

c# - 如何在 .NET Core 的 Startup 类构造函数中访问 AppSettings

Serilog - AppSettings MinLevel 不工作

windows-services - 指定 Serilog 滚动文件路径的目录

asp.net - 在 Microsoft Windows Azure 上设置网站的默认网页