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

时间:2017-12-12 10:41:08

标签: c# logging asp.net-core stack-trace serilog

所以我最近开始构建一个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中的构造函数注入将类注入到类的构造函数中时,它会记录堆栈跟踪。例如:

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[] )

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

1 个答案:

答案 0 :(得分:7)

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