Konrad
Konrad

Reputation: 4812

Logging in ASP.NET Core Main

I've an ASP.NET Core 3 WebAPI with a simple Main and a CreateHostBuilder.

public static void Main(String[] args)
{
   CreateHostBuilder(args).Build().Run();
}

Later logging in my controllers etc. works fine.

But how can I log possible errors in the Main?

Upvotes: 2

Views: 1449

Answers (3)

Dmitry Filippov
Dmitry Filippov

Reputation: 11

For Net 6.0, this gist works for me https://gist.github.com/filippovd/edc28b511ef0d7dae9ae8f6eb54c30ed

var builder = WebApplication.CreateBuilder(args);

var logger = LoggerFactory
    .Create(loggingBuilder =>
    {
        // Copy all the current providers that was set within WebApplicationBuilder
        foreach (var serviceDescriptor in builder.Logging.Services)
            {
            loggingBuilder.Services
                .Add(serviceDescriptor);
        }
    })
    .CreateLogger<Program>();
;

// Add services to the container.
logger.LogInformation("Add services to the container...");


// Console
// ....
info: Program[0]
      Add services to the container...

Upvotes: 1

Stokely
Stokely

Reputation: 15927

Another way.....the advantage to this one is this is a separate logger from the HostBuilder's, so it can log things before the Host is even built. It also can be used throughout the class and outside Main in Program.cs. The disadvantage is it cant use the appsettings.json file to configure it (unless someone can show me how).

public class Program
{
    // The Program console apps private logger
    private static ILogger _logger;
    public static void Main(string[] args)
    {
        // Now create a logging object for the Program class.
        ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder
        .AddConsole()
        .AddDebug()
        );
        _logger = loggerFactory.CreateLogger<Program>();
        _logger.LogInformation("PROGRAM CLASS >>> The Program Console Class has started...");
    }
}

Upvotes: 4

Muhammad Hannan
Muhammad Hannan

Reputation: 2567

You can get get the logger using

// Build the host and configurations
var host = CreateWebHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
    // Get the registered logger service
    var logger = scope.ServiceProvider.GetRequiredService<ILogger<YourClassName>>();
    logger.LogInformation("Logger test");
}
// finally run the host 
host.Run();

Upvotes: 2

Related Questions