2022-10-31

Use logger in custom classes in my console application with Dependency Injection

I have a console application, and I added logger builder as follows in Program.cs:

using var loggerFactory = LoggerFactory.Create(builder =>
    {
        builder
            .AddFilter("Microsoft", LogLevel.Warning)
            .AddFilter("System", LogLevel.Warning)
            .AddConsole();
    });
    ILogger logger = loggerFactory.CreateLogger<Program>();

Now say I have many classes in the project and all want to use logger. How can I make it available to other classes?

For example, I have:

internal class Test
{
    public Test()
    {
        //use logger here
        //logger.LogInformation("Calling Test");
    }
}

In certain kinds of projects such as Azure Functions, the logger is readily injected in the functions, is there a similar way I can do it in Console application?



No comments:

Post a Comment