ASP.NET Core 2.0使用Serilog在抛出异常时记录堆栈跟踪

Jer*_*oen 8 c# logging stack-trace serilog asp.net-core

所以我最近开始构建一个asp.net核心应用程序,并且我正在使用SeriLog进行日志记录.这工作正常,直到最近我发现大多数情况下异常的堆栈跟踪没有转移到我的日志.我正在使用.WriteTo.RollingFile()方法在Startup.cs中的LoggerConfiguration中写入.txt文件,如此

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();
}
Run Code Online (Sandbox Code Playgroud)

在我的loggerFactory中,我添加了这行代码的Serilog

loggerFactory.AddSerilog();
Run Code Online (Sandbox Code Playgroud)

我的BuildWebHost方法没有.UserSerilog(),如下所示:

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

这个方法作为MainProgram.cs 中我方法的最后一步被调用.阅读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);
Run Code Online (Sandbox Code Playgroud)

这个日志:

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
Run Code Online (Sandbox Code Playgroud)

它没有堆栈跟踪.但是,例如,当我忘记通过我的.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[] )
Run Code Online (Sandbox Code Playgroud)

如何让stacktrace显示在我的日志.txt文件中?

Cod*_*ler 9

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);
Run Code Online (Sandbox Code Playgroud)

你打电话的时候

_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);
Run Code Online (Sandbox Code Playgroud)