有没有办法用方法名称来丰富所有 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/