Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net-6.0

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?

like image 390
Bunnynut Avatar asked Feb 05 '26 12:02

Bunnynut


1 Answers

If you're using a minimal hosting model, it`s pretty simple:

...
var app = builder.Build();
app.Logger.LogInformation("Starting Application");
...

The preceding code is show in the official ASP.NET Core docs

like image 130
Vitaliy Ulantikov Avatar answered Feb 07 '26 02:02

Vitaliy Ulantikov