'How to create a Logger in .NET 6 Program.cs

I have a Data.Migrations project, which will run any Entity Framework Migrations to update the database model. Recently I have updated this project to .NET 6 and added a logger to the Program.cs using the following code:

var serviceCollection = new ServiceCollection();
var serviceProvider = serviceCollection.BuildServiceProvider();
_logger = serviceProvider.GetService<ILogger<Program>>();

This results however in _logger == null.

How can I add a logger to the Program.cs?



Solution 1:[1]

You are missing this line:

serviceCollection.AddLogging();

So the full code would look like this:

var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging();
var serviceProvider = serviceCollection.BuildServiceProvider();
_logger = serviceProvider.GetService<ILogger<Program>>();

Solution 2:[2]

Visual Studio complains with the following error Compiler Error CS0246. It does not recognise Program

Solution 3:[3]

As mentioned in the above answer by @Olegi, the logger for Program.cs can be created. However if this logger has to log in the logging providers configured on the WebApplicationBuilder, below line can be used

var logger = builder.Logging.Services.BuildServiceProvider().GetRequiredService<ILogger<Program>>();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OlegI
Solution 2 Jason
Solution 3 Jatin