ASP.NET Core 2.0使用Serilog记录堆栈跟踪信息当异常抛出

22

最近我开始构建一个asp.net core应用程序,在日志记录方面我使用了SeriLog。这一切都很正常,直到最近我发现大多数情况下异常的堆栈跟踪信息并未传递到我的日志中。我在Startup.cs中的LoggerConfiguration中使用.WriteTo.RollingFile()方法将日志写入一个.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

And in my loggerFactory I added the Serilog with this line of code

loggerFactory.AddSerilog();

我的BuildWebHost方法没有.UserSerilog(),看起来是这样的:

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

这个方法在我的Program.csMain方法中作为最后一步被调用。 根据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进行构造函数注入将类注入类的构造函数时,它会记录堆栈跟踪。例如:

它不包含堆栈跟踪。但是,例如,如果我忘记通过从我的 .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文件中?

1个回答

34

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

当你调用时,实际上使用的是第二个参数,并将ex对象作为格式化的参数传递。只要你的消息没有格式化项,传递的异常就会被忽略。

要解决这个问题,只需在调用中切换参数,将异常放在第一位:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接