Bunnynut
Bunnynut

Reputation: 1328

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?

Upvotes: 14

Views: 29899

Answers (4)

Parth Sekar
Parth Sekar

Reputation: 418

Are you not considering SeriLog? I found it quite useful for my work. It comes with good support for structured logging and log level filtering. The UseSerilog extension comes handy. More on Logging here.

A word of advice. Don't use BuildServiceProvider. It is a potential code smell.

Added some reference links from the author of "ASP .Net core in action" book.

Disclaimer: I am not associated with Andrew Lock by any means though I would love to. The man does write good articles on .Net.

Upvotes: 1

Vitaliy Ulantikov
Vitaliy Ulantikov

Reputation: 10514

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

Upvotes: 12

Jatin
Jatin

Reputation: 91

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

Upvotes: 2

OlegI
OlegI

Reputation: 6010

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

Upvotes: 11

Related Questions