Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 639
Maxim Avatar asked Jul 20 '17 16:07

Maxim


People also ask

What is logging in coding?

Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging, and running. If you don't have any logging record and your program crashes, there are very few chances that you detect the cause of the problem.

What is ILoggerFactory C#?

Registers a wrapper logger which provides a common way to filter log messages across all registered ILoggerProviders. CreateLogger(ILoggerFactory, Type) Creates a new ILogger instance using the full name of the given type . CreateLogger<T>(ILoggerFactory)


2 Answers

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/

like image 161
Maxim Avatar answered Sep 28 '22 03:09

Maxim


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.
like image 28
Leniel Maccaferri Avatar answered Sep 28 '22 03:09

Leniel Maccaferri