gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:50:40 24 4
gpt4 key购买 nike

我正在使用简单的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com