1

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

1 Answer 1

3

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" />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.