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

标签 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 中的构造函数注入(inject)将一个类注入(inject)到类的构造函数中时,它会记录堆栈跟踪。例如:

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("尝试将客户 View 模型转换为模型或从 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);

关于c# - ASP.NET Core 2.0 在抛出异常时使用 Serilog 记录堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47770579/

相关文章:

Java logback 嵌套变量替换

logging - 将 screen (程序)输出保存到文件

.net - 解决错误 "Microsoft.NETCore.App 1.0.0 does not support framework .NETFramework,Version=v4.6.1"

c# - 'IServiceCollection' 不包含 'AddMvc' 的定义, 'IApplicationBuilder' 不包含 'UseStaticFiles' 的定义,

c# - WPF 和 Prism 的通用对话框窗口

c# - 创建实用程序类?

c# - Entity Framework 5 如何在存在关系时执行创建/更新

javascript - 确定 razor 生成 View 中 html 表的大小

python - 如何使用自定义处理程序为模块显示 Python 日志消息

security - 使用 IP 地址的 JWT 安全性