user10634744
user10634744

Reputation:

Log within whole program

How do I log everywhere in the program, without having to declare ILogger parameter in every class? I would like best practice to log everywhere within program.

MyClass(ILogger<MyClass> logger)
{
    _logger = logger;
}

Should I utilize a static class as described here?

public class ApplicationLogging
{
    private static ILoggerFactory _Factory = null;

    public static void ConfigureLogger(ILoggerFactory factory)
    {
        factory.AddDebug(LogLevel.None).AddStackify();
        factory.AddFile("logFileFromHelper.log"); //serilog file extension
    }

    public static ILoggerFactory LoggerFactory
    {
        get
        {
            if (_Factory == null)
            {
                _Factory = new LoggerFactory();
                ConfigureLogger(_Factory);
            }
            return _Factory;
        }
        set { _Factory = value; }
    }
    public static ILogger CreateLogger() => LoggerFactory.CreateLogger();
}    

Upvotes: 1

Views: 394

Answers (1)

Moerwald
Moerwald

Reputation: 11254

I think it's not a good idea to use a logger a static dependency. Personally, I would inject it in the constructor of the class. Why? Well, static dependencies in form of a static property have the following problems:

  • In the case of unit tests, they are hard to mock. If you inject the logger in the CTOR you can libs like Moq to change the logging to e.g. stdout (ok, that's also possible with e.g. log4net's config file).

  • Using static properties can make your code "non-determistic". Why? A static property is initialized when the class is referenced the first time. So if you change your code the static property initialization may be called earlier or later. If you've a bug in the initialization it will be hard to find. Why? Because you've no logging.

  • If you want to change the logging framework, you've to find all static references to it. Ok, that's not a that hard task with grep or modern IDEs. However, if you inject the logger dependency the compiler will show (based on the compile errors) which lines of code you've to change (simply remove the logger reference from the solution file).

Hope that helps.

Upvotes: 1

Related Questions