vb.net Serilog - 使用 MethodName 输出/丰富所有消息,从中调用日志条目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29470863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:58:10  来源:igfitidea点击:

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

vb.netserilog

提问by Aaron Glover

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

无论如何,是否可以使用方法名称来丰富所有 Serilog 输出。

For Instance consider If I have the following;

例如考虑如果我有以下内容;

Public Class MyClassName

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

End Class

The desired output would be as follows;

所需的输出如下;

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

Actually the Fully Qualified Name would be good.

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

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

It seems that "Enrichers" are only good for Static Information and won't work each time.

似乎“Enrichers”只对静态信息有用,每次都不起作用。

回答by MovGP0

in case you need a version in C#:

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

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

回答by Nicholas Blumhardt

It's possible to do this with an enricher by reflecting over the call stack, but very expensive to do so, so Serilog doesn't offer it.

可以通过反射调用堆栈来使用丰富器来做到这一点,但这样做非常昂贵,因此 Serilog 不提供它。

Instead you can use something like:

相反,您可以使用以下内容:

Logger.Here().Information("Hello, world!");

and implement the Here()method as an extension method on ILogger:

并将该Here()方法作为扩展方法实现ILogger

<Extension>
Public Sub Here(ByVal logger as ILogger,
    <CallerMemberName> Optional memberName As String = Nothing)

    Return logger.ForContext("MemberName", memberName)
End Sub 

回答by litetex

Based on MovGP0's answer(for C#),

基于MovGP0 的回答(对于 C#),

I created a solution that doesn't require the Here()-Method in every line where you want to log, by simply adding a custom Log.cs-Class into the "root namespace" of a project.

我创建了一个解决方案,它不需要在Here()要记录的每一行中使用-Method,只需将自定义Log.cs-Class添加到项目的“根命名空间”中即可。

For more info see: https://gist.github.com/litetex/b88fe0531e5acea82df1189643fb1f79

有关更多信息,请参阅:https: //gist.github.com/litetex/b88fe0531e5acea82df1189643fb1f79

回答by Jaya B.

In outputTemplate for the Serilog , configure for logs to write Properties. Method name will be written as part of ActionNamecolumn.

在 Serilog 的 outputTemplate 中,配置要写入的日志Properties。方法名称将作为ActionName列的一部分写入。

ActionNamecan also be configured individually (instead of all properties) in outputTemplate.

ActionName也可以在 outputTemplate 中单独配置(而不是所有属性)。

Configuring Properties/ActionNamewill write the method name in Namespace.ClassName.MethodNameformat.

配置Properties/ActionName将以Namespace.ClassName.MethodName格式写入方法名称 。

回答by Sergey Fasolko

The version on C# could be simplified. Just use AutofacSerilogIntegration:

C# 上的版本可以简化。只需使用 AutofacSerilogIntegration:

var path = Server.MapPath("~/");

        var outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext} {Message} {NewLine}{Exception}";
        Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Debug()
                    .WriteTo.File($"{path}/log/serilog-.log", LogEventLevel.Debug, outputTemplate, rollingInterval: RollingInterval.Day)
                    .CreateLogger();

        var builder = new ContainerBuilder();
        builder.RegisterLogger();  // from AutofacSerilogIntegration
        builder.RegisterControllers(typeof(MvcApplication).Assembly);
        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));