programing

Serilog - 로그 항목이 호출된 MethodName을 사용하여 모든 메시지 출력/리치

telecom 2023. 5. 10. 20:16
반응형

Serilog - 로그 항목이 호출된 MethodName을 사용하여 모든 메시지 출력/리치

메서드 이름으로 모든 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();

통화 스택에 반영함으로써 더 풍부한 기능을 사용하여 이를 수행할 수 있지만, 그렇게 하는 데는 매우 비용이 많이 들기 때문에 Serilog는 이 기능을 제공하지 않습니다.

대신 다음과 같은 것을 사용할 수 있습니다.

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

그리고 그것을 구현.Here()확장 방법으로서의 방법ILogger:

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

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

MovGP0의 답변(C#의 경우)을 기준으로,

필요 없는 솔루션을 개발했습니다.Here()- 사용자 정의를 추가하기만 하면 기록할 모든 줄에 있는 방법Log.cs-프로젝트의 "루트 네임스페이스"로 분류합니다.

자세한 내용은 https://gist.github.com/litetex/b88fe0531e5acea82df1189643fb1f79 를 참조하십시오.

출력중Serilog용 템플릿, 기록할 로그 구성Properties메서드 이름은 다음의 일부로 기록됩니다.ActionName기둥.

ActionName출력에서 (모든 속성 대신) 개별적으로 구성할 수도 있습니다.템플릿.

구성 중Properties/ActionName메서드 이름을 에 씁니다.Namespace.ClassName.MethodName서식을 정하다

C#의 버전은 단순화될 수 있습니다.AutofacSerilog만 사용합니다.통합:

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

언급URL : https://stackoverflow.com/questions/29470863/serilog-output-enrich-all-messages-with-methodname-from-which-log-entry-was-ca

반응형