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

Mug*_*gen 7 c# asp.net-core

我使用的是简单的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");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何配置日志记录:

var host = new HostBuilder().ConfigureLogging(ConfigureLogging)...
...
await host.RunAsync();
Run Code Online (Sandbox Code Playgroud)
        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();
        }
Run Code Online (Sandbox Code Playgroud)

应用程序设置:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "FileLoggingOptions": {
    "FileName": "app-",
    "LogDirectory": "logs",
    "FileSizeLimit": 10485760,
    "Extension": "log"
  }
}
Run Code Online (Sandbox Code Playgroud)

sil*_*ire 29

如果您的记录器没有记录异常,也可能是因为您不小心弄错了传递参数的顺序:

_logger.LogError("An error occurred", e)     // WRONG: Exception will not be logged
Run Code Online (Sandbox Code Playgroud)

正确的顺序是始终提供异常对象作为第一个参数:

_logger.LogError(e, "An error occurred")     // OK: Will log the exception
Run Code Online (Sandbox Code Playgroud)

参考:

https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/#always-pass-exception-as-first-parameter


Mug*_*gen 9

请参阅默认值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();
        }
Run Code Online (Sandbox Code Playgroud)

它只是忽略异常...我实现了一个自定义控制台记录器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

public static Task Main(string[] args)
    => WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(...)
        .ConfigureServices(...)
        .ConfigureLogging((hostContext, loggingBuilder) => loggingBuilder.AddProvider(new ConsoleLoggerProvider()))
        .UseStartup<Startup>()
        .Build()
        .RunAsyncSafe();
Run Code Online (Sandbox Code Playgroud)

  • @granadaCoder 是的,但这需要始终记住添加 `+ ex.Message` 并且也不会打印堆栈跟踪 (4认同)