loggingasp.net-core.net-coreasp.net-core-mvc

Logging within Program.cs


Is it possible to get an ILogger inside Program.cs Main method? I want to pass it on to a service that's created inside that method.

I've only found this on SO How do I write logs from within Startup.cs , but that's logging within Startup.cs.


Solution

  • 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/