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