Logging within Program.cs

2019-03-27 02:14发布

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.

2条回答
啃猪蹄的小仙女
2楼-- · 2019-03-27 03:03

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.
查看更多
SAY GOODBYE
3楼-- · 2019-03-27 03:04

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/

查看更多
登录 后发表回答