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

ASP.NET Core 2.0 using Serilog to log stacktrace when exception is thrown

所以我最近开始构建一个 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();
}

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

loggerFactory.AddSerilog();

我的 BuildWebHost 方法没有 .UserSerilog() 并且看起来像这样:

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

此方法作为我在 Program.cs 中的 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 中的构造函数注入将 class 注入到 class 的构造函数中时,它会记录堆栈跟踪。例如:

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 文件中?

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