Search code examples
c#loggingasp.net-coreserilog

Serilog in program class


I am trying to log with Serilog in an ASP.NET Core application's Program.cs class. My current setup is as follows:

public class Program
{
    public static void Main(string[] args)
    {
        DoStuff();
        CreateWebHostBuilder(args).Build().Run();
    }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, builder) =>
            {
                builder.AddFile(@"C:\...\log-{Date}.txt", isJson: true);
            })
            .UseStartup<Startup>();
}

I can successfully log in a Controller class by doing:

public class WebhookController : Controller
{
    readonly ILogger<WebhookController> _log;
    public WebhookController(ILogger<WebhookController> log)
    {
        _log = log;
    }
    public IActionResult Index()
    {
        _log.LogInformation("hello world");
        return View();
    }
}

However, when trying to replicate this in the program class, _log is not accessible in Main(string[] args):

public class Program
{
    readonly ILogger<Program> _log;
    public Program(ILogger<Program> log)
    {
        _log = log;
    }

    public static void Main(string[] args)
    {
        DoStuff();
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, builder) =>
            {
                builder.AddFile(@"C:\...\log-{Date}.txt", isJson: true);
            })
            .UseStartup<Startup>();
}

How can I configure Serilog to log in the program class?


Solution

  • When the web host is built, the IWebHost exposes IWebHost.Services Property

    public IServiceProvider Services { get; }
    

    which can be used to resolve the desired dependencies.

    public class Program {
    
        public static void Main(string[] args) {
            var webHost = CreateWebHostBuilder(args).Build();
            var services = webHost.Services;
    
            var log = services.GetService<ILogger<Program>>();
    
            DoStuff(log);
    
            webHost.Run();
        }
    
        static void DoStuff(ILogger<Program> log) {
            //...
        }
    
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureLogging((hostingContext, builder) =>
                {
                    builder.AddFile(@"C:\...\log-{Date}.txt", isJson: true);
                })
                .UseStartup<Startup>();
    }
    

    Remember to include using Microsoft.Extensions.DependencyInjection; in order to have access to the .GetService<T>() extension method on IServiceProvider.