Search code examples
.net-coreilogger

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


ILogger Factory is not logging using static instance.I want to invoke ILogger inside static methods of Class project.Can anyone help me to fix this below code.

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();
    }
}

Solution

  • Making the logging class static is not a bad idea, so:

        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. Make it static
    2. Rename Your logger factory to Another name because LoggerFactory is the name of System class name
    3. Add Console Logger or any other Logging Provider
    4. Config the provider to show logging information sample

    Project References:

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