2017-12-12 36 views
2

그래서 최근에 asp.net 핵심 응용 프로그램을 빌드하고 로깅을 위해 SeriLog를 사용하기 시작했습니다. 최근까지 예외의 stacktrace가 내 로그로 전송되지 않는다는 사실을 알게되었을 때까지 제대로 작동했습니다. 그래서ASP.NET 코어 2.0 예외를 throw 할 때 Stacktrace를 기록하기 위해 Serilog를 사용합니다.

public void ConfigureServices(IServiceCollection services) 
{ 
    //add a bunch of services 

    services.AddLogging(builder => 
    { 
     builder.AddConsole(); 
     builder.AddDebug(); 

     var logger = new LoggerConfiguration() 
      .MinimumLevel.Verbose() 
      .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) 
      .Enrich.WithExceptionDetails() 
      .WriteTo.RollingFile(Configuration.GetValue<string>("LogFilePath") + "-{Date}.txt", LogEventLevel.Information, 
       outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}) {Message}{NewLine}{Exception}") 
      .CreateLogger(); 

     builder.AddSerilog(logger); 
    }); 

    services.AddMvc(); 
} 

처럼 Startup.cs 내 LoggerConfiguration에 .txt 파일에 쓰기 그리고 내 loggerFactory에 내가 코드

의이 라인으로 Serilog을 추가하기 위해 .WriteTo.RollingFile() 메소드를 사용하고 있습니다 .UserSerilog을 (이)하지 않고
loggerFactory.AddSerilog(); 

내 BuildWebHost 방법은 다음과 같습니다

public static IWebHost BuildWebHost(string[] args) => 
     WebHost.CreateDefaultBuilder(args) 
      .UseStartup<Startup>() 
      .Build(); 

이 방법은 Program.cs 01 내 Main 방법의 마지막 단계에서 호출되는Serilog의 설명서를 읽으면 RollingFile의 outputTemplate에있는 {Exception}도 예외의 스택 추적을 기록해야합니다. 예를 들어 내가 그렇게합니다 (Microsoft.Extensions.Logging.ILogger 사용)처럼

_log.LogError("Exception thrown when trying to convert customer viewmodel to model or getting data from the database with id: " + id, ex); 

을 오류를 기록 그러나이 기록합니다

2017-12-12 10:59:46.871 +01:00 [Error] (ProjectName.Controllers.CustomersController) Exception thrown when trying to convert customer viewmodel to model or getting data from the database with id: 137dfdc1-6a96-4621-106c-08d538a26c5b 

그것은 스택 트레이스가 없습니다. 하지만 예를 들어, .addServices에서 생성자 주입을 통해 클래스의 생성자에 클래스를 삽입하는 것을 잊어 버리면 스택 추적을 기록합니다. 예 :

2017-12-12 11:03:23.968 +01:00 [Error] (Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware) An unhandled exception has occurred while executing the request 
System.InvalidOperationException: Unable to resolve service for type 'TypeName' while attempting to activate 'ProjectName.Controllers.CustomersController'. 
    at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired) 
    at lambda_method(Closure , IServiceProvider , Object[]) 

로깅 .txt 파일에 스택 트레이스를 표시하려면 어떻게해야합니까?

답변

2

LogError 확장 방법은 다음과 무시가 있습니다

public static void LogError(this ILogger logger, Exception exception, string message, params object[] args); 
public static void LogError(this ILogger logger, string message, params object[] args); 

당신은 당신이 실제로 두 번째를 사용

_log.LogError("Exception thrown when trying to convert customer viewmodel to model or getting data from the database with id: " + id, ex);

를 호출하고 ex 객체가 단지 형식에 대한 매개 변수로 전달됩니다. 메시지에 서식 지정 항목이없는 한 전달 된 예외는 무시됩니다.

은 당신의 호출에 인수를 전환 문제를 해결하려면, 예외가 먼저해야합니다 그것 뿐이다

_log.LogError(ex, "Exception thrown when trying to convert customer viewmodel to model or getting data from the database with id: " + id); 
+0

이런 젠장는. 그리고 그것은 간단합니다. 감사! – Jeroen