我使用的是通过依赖注入获得的简单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"
}
}发布于 2019-09-19 16:51:08
请参见默认的MessageFormatter:https://github.com/aspnet/Logging/blob/master/src/Microsoft.Extensions.Logging.Abstractions/LoggerExtensions.cs
private static string MessageFormatter(FormattedLogValues state, Exception error)
{
return state.ToString();
}它只是忽略了例外..。我实现了一个自定义控制台记录器:
public class ConsoleLoggerProvider : ILoggerProvider
{
public void Dispose()
{
}
public ILogger CreateLogger(string categoryName)
=> new ConsoleLogger(categoryName);
private class ConsoleLogger : ILogger
{
private readonly string _categoryName;
public ConsoleLogger(string categoryName)
=> _categoryName = categoryName;
public void Log<TState>(
LogLevel logLevel, EventId eventId, TState state, Exception exception,
Func<TState, Exception, string> formatter
)
{
if (!IsEnabled(logLevel))
{
return;
}
Console.WriteLine(
$"{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} [{logLevel}] {_categoryName}: {state}{(exception != null ? "\n" : string.Empty)}{exception}"
);
}
public bool IsEnabled(LogLevel logLevel)
=> true;
public IDisposable BeginScope<TState>(TState state)
=> null;
}
}并利用它:
public static Task Main(string[] args)
=> WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(...)
.ConfigureServices(...)
.ConfigureLogging((hostContext, loggingBuilder) => loggingBuilder.AddProvider(new ConsoleLoggerProvider()))
.UseStartup<Startup>()
.Build()
.RunAsyncSafe();发布于 2021-07-12 18:09:02
如果您的记录器没有记录异常,也可能是因为您意外地把传递参数的顺序弄错了:
_logger.LogError("An error occurred", e) // WRONG: Exception will not be logged正确的顺序是始终以第一个参数的形式提供异常对象:
_logger.LogError(e, "An error occurred") // OK: Will log the exception参考资料:
https://stackoverflow.com/questions/58010923
复制相似问题