在 asp.net 核心中使用 ILogger 的静态实例进行日志记录不起作用

Logging using static instance of ILogger in asp.net core do not work

ILogger Factory 没有使用静态记录 instance.I 想在 Class 的静态方法中调用 ILogger project.Can 谁能帮我解决下面的代码。

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.LogInformation("Hello World!");
        Console.Read();
    }
}

使日志记录 class 静态化是个不错的主意,因此:

    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 是系统 class 名称
  3. 的名称
  4. 添加控制台记录器或任何其他日志记录提供程序
  5. 配置提供程序以显示日志信息示例

项目参考:

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