Maxim
Maxim

Reputation: 1132

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.

Upvotes: 38

Views: 42689

Answers (7)

Tod
Tod

Reputation: 2524

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.

Upvotes: 10

Anish Kutti
Anish Kutti

Reputation: 354

Program.cs

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Log4Net.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

builder.Logging.AddLog4Net();

Above worked for me in .net 6

Thanks to: https://onloupe.com/blog/does-log4net-work-on-net6/

Upvotes: -2

RickAndMSFT
RickAndMSFT

Reputation: 22800

See the official doc Log in Program.cs

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Logger.LogInformation("Adding Routes");
app.MapGet("/", () => "Hello World!");
app.Logger.LogInformation("Starting the app");
app.Run();

Upvotes: 13

Aathira
Aathira

Reputation: 813

Following helped me to add logger for program.cs as well as for any of the static classes

private static void TemporaryLogger(string methodName, string lineNumber)
    {
        var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
        var logger = loggerFactory.CreateLogger(string.Empty);
        logger.LogInformation($"Test Logger for  class className: Identifier - {methodName} : Line number - {lineNumber}");
    }

Upvotes: 1

Kraego
Kraego

Reputation: 3882

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");

Upvotes: 6

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102408

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.

Upvotes: 20

Maxim
Maxim

Reputation: 1132

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/

Upvotes: 27

Related Questions