c# - Microsoft.Extensions.Logging - LogError 未记录异常

标签 c# asp.net-core

我正在使用简单的 ASP.NET提供了我通过依赖注入(inject)获得的记录器:Microsoft.Extensions.Logging.ILogger<T> .实际上动态类型是Microsoft.Extensions.Logging.Logger<T> .

捕获异常时,我尝试使用以下命令记录它们:_logger.LogError(exception, "message") ,但是只打印消息。

namespace App
{
    public class App : IApp
    {
        private readonly ILogger<App> _logger;

        public PomParser(ILogger<App> logger)
            => _logger = logger;

        public void DoStuff()
        {
            try
            {
                DoStuffUnsafe();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex,"Failed to do stuff");
            }
        }
    }
}

我如何配置日志记录:
var host = new HostBuilder().ConfigureLogging(ConfigureLogging)...
...
await host.RunAsync();
        private static void ConfigureLogging(HostBuilderContext hostContext, ILoggingBuilder configLogging)
        {
            configLogging.ClearProviders();
            configLogging.AddConfiguration(hostContext.Configuration.GetSection("Logging"));
            configLogging.AddFile(
                options =>
                {
                    hostContext.Configuration.GetSection("FileLoggingOptions")
                        .Bind(options);
                }
            );
            configLogging.AddConsoleLogger();
        }

应用设置:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "FileLoggingOptions": {
    "FileName": "app-",
    "LogDirectory": "logs",
    "FileSizeLimit": 10485760,
    "Extension": "log"
  }
}

最佳答案

如果您的记录器没有记录异常,也可能是因为您不小心混淆了记录方法的参数顺序:

_logger.LogError("An error occurred", e)     // WRONG: Exception will not be logged
正确的顺序是始终提供异常对象作为第一个参数:
_logger.LogError(e, "An error occurred")     // OK: Will log the exception

关于c# - Microsoft.Extensions.Logging - LogError 未记录异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58010923/

相关文章:

c# - iTextSharp - 如何获取用于签名的 PDF 内容,然后稍后再签名

c# - DSharpPlus 编辑 channel 主题

c# - ASP.NET Core Controller 中奇怪的死锁情况

c# - 如何修复 Automapper 将连接表映射到 ViewModel

asp.net-core - 基本bproject创建无法创建Prime Nuget缓存

c# - 使用 Fiddler 填充属性 [FromForm] 的参数

c# - 使用 EF 处理嵌套表

c# - 将 c#/WPF GUI 围绕 c++/cli 围绕 native c++ 包装

c# - 创建项目而不使用单个 TRY-CATCH 异常处理

c# - node.js vs ASP.NET Core 性能测试的意外结果