Logging within Program.cs

Accidentally stumbled upon the answer after googling a bit more.

using System;
using Microsoft.Extensions.Logging;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var logFactory = new LoggerFactory()
            .AddConsole(LogLevel.Debug)
            .AddDebug();

            var logger = logFactory.CreateLogger<Type>();

            logger.LogInformation("this is debug log");
        }
    }
}

Kudos to https://askguanyu.wordpress.com/2016/09/26/net-core-101-e06-net-core-logging/


What worked for me in combination with serilog based on the default template of Program.cs (.NET 6.0), was nearly the same approach as the one of Leniel Maccaferri.

ILogger logger = builder.Services.BuildServiceProvider().GetRequiredService<ILogger<Program>>();
logger.LogInformation("This is a testlog");

New in .net Core 6 (* I have no idea if this was new to.net core 6, 5 or 3 *)

var logger = LoggerFactory.Create(config =>
    {
        config.AddConsole();
        config.AddConfiguration(builder.Configuration.GetSection("Logging"));
    }).CreateLogger("Program");

This was my simple starting point, you don't actually have to pickup the Configuration section for logging, but I figured it makes sense. But you do need to specify an output; Console, although default for DI is not assumed in the factory.


This is how I managed to get the ILogger interface configured in Startup.cs (in my case Log4Net) working when inside Program.cs:

public static void Main(string[] args)
{
    var host = BuildWebHost(args);

    ILogger logger = host.Services.GetService<ILogger<Program>>();

    try
    {
        logger.LogInformation("Starting web host");

        host.Run();
    }
    catch (Exception ex)
    {
        logger.LogCritical(ex, "Starting web host failed.");
    }
}
  • Add using Microsoft.Extensions.DependencyInjection; so that the generic type in GetService works as expected.