Dotnet Logger without DI

Loggers within Dotnet are usually optained via Dependency Injection. If you ever find yourself needing one outside places where DI can create one, you can use LoggerFactory.


public class Utilities
{
    public static ILogger<T> CreateLogger<T>()
    {
        using var loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
        });

        return loggerFactory.CreateLogger<T>();
    }
}

Then you can create as many loggers as desired:

public class Example {
    ILogger<Example> logger;

    Example()
    {
        this.logger = Utilities.CreateLogger<Example>();
    }
}

AddConsole is required for console output. Without it you might log but not see anything on the terminal. You must add Microsoft.Extensions.Logging.Console package for it to work:

dotnet add package Microsoft.Extensions.Logging.Console