我正在使用通过依赖注入获取的简单ASP.NET
提供的日志记录器: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"
}
}
configLogging.ClearProviders();
,所以除非你再次显式添加它们,否则所有内置的日志记录器都将消失。因此,你看不到控制台日志,因为没有控制台记录器。 - poke