在ASP.NET Core中使用ILogger的静态实例进行日志记录不起作用

问题描述

ILogger工厂未使用静态实例进行日志记录。我想在Class项目的静态方法调用ILogger。有人可以帮我修复以下代码吗?

public class AppLogger
{
    public static ILoggerFactory LoggerFactory { get; set; } = new LoggerFactory();
    public static ILogger CreateLogger<T>() => LoggerFactory.CreateLogger<T>();
    public static ILogger CreateLogger(string categoryName) => LoggerFactory.CreateLogger(categoryName);
}
class Program
{
    public static readonly ILogger _logger = AppLogger.CreateLogger<Program>();

    static void Main(string[] args)
    {
        _logger.Log@R_337_4045@ion("Hello World!");
        Console.Read();
    }
}

预先感谢

解决方法

使Logging类成为静态不是一个坏主意,所以:

public static class AppLogger
{
    // LoggerFactory is the name of system class; So,It's not a good idea to use it again.
    public static ILoggerFactory MyLoggerFactory { get; set; } = LoggerFactory.Create(builder =>
    {
        // Add Console Logger and config to show log level information
        builder.AddConsole(configure: config => { builder.SetMinimumLevel(LogLevel.Information); });
    });

    public static ILogger CreateLogger<T>() => MyLoggerFactory.CreateLogger<T>();
    public static ILogger CreateLogger(string categoryName) => MyLoggerFactory.CreateLogger(categoryName);
}
  1. 将其设为静态
  2. 将您的记录器工厂重命名为另一个名称,因为LoggerFactory是系统类名称的名称
  3. 添加控制台日志记录器或任何其他日志记录提供程序
  4. 配置提供程序以显示日志记录信息示例

项目参考:

<PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.8" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.8" />