How to pass a Logger to the Startup class in an ASP.NET 5.0 app?

Viewed 4518

In ASP.NET 5.0, we can now define a factory method for controlling the activation of the Startup class.

In the demo example provided by Microsoft, they create a logger and then pass this into the Startup class:

public class Program
{
    public static async Task Main(string[] args)
    {
        var logger = CreateLogger(); // <--- HERE !!!!

        var host = Host.CreateDefaultBuilder()
            .ConfigureWebHost(builder =>
            {
                builder.UseStartup(context => new Startup(logger)); // Logger passed into the ctor
            })
            .Build();

        await host.RunAsync();
    }
}

However, I am not sure how the author created the Logger (ie. the code in that method), which hopefully will be an ILogger.

2 Answers

However, I am not sure how the author created the Logger (ie. the code in that method), which hopefully will be an ILogger.

It's the same as always (fortunately). First, create and configure a logger factory:

var loggerFactory = LoggerFactory.Create(builder => { /*configure*/ });

Then, get a logger out of it:

var startupLogger = loggerFactory.CreateLogger<Startup>();

The above is just one way and there are multiple, both built-in and with the several third-party logging frameworks. Read more in the main Logging in .NET Core and ASP.NET Core document.

You need to wire it up in ConfigureLogging (Namespace: Microsoft.Extensions.Hosting) extension:

        private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureLogging(builder =>
            {
                builder.AddNLog(); //<-I used Nlog for demonstration purposes. This will take care things for you.
                //builder.AddConsole();
                //builder.AddDebug();
            })
            .ConfigureWebHostDefaults(builder =>
            {
                builder.UseStartup<Startup>(); //<Startup class
            });

Use dependency injection via your constructor:

private readonly ILoggerFactory loggerFactory;
public Class1(ILoggerFactory loggerFactory)
{
    this.loggerFactory = loggerFactory;
}

public SomeMethod(){
    var logger = loggerFactory.CreateLogger("Exception logger"); //<-You can call create logger here
}
  • I would suggest you decide first, which logging framework you want to use, popular loggers provides rich documentations that will help you hit the ground running.
Related