简体   繁体   English

如何在 .NET 6 Program.cs 中创建记录器

[英]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.我有一个 Data.Migrations 项目,它将运行任何实体框架迁移来更新数据库 model。 Recently I have updated this project to .NET 6 and added a logger to the Program.cs using the following code:最近我已将此项目更新为 .NET 6,并使用以下代码向Program.cs添加了一个记录器:

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

This results however in _logger == null .然而,这会导致_logger == null

How can I add a logger to the Program.cs?如何将记录器添加到 Program.cs?

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

If you're using a minimal hosting model, it`s pretty simple:如果您使用的是最小托管 model,则非常简单:

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

The preceding code is show in the official ASP.NET Core docs前面的代码显示在官方ASP.NET 核心文档

Visual Studio complains with the following error Compiler Error CS0246. Visual Studio 抱怨以下错误编译器错误 CS0246。 It does not recognise Program它不识别程序

As mentioned in the above answer by @Olegi, the logger for Program.cs can be created.正如@Olegi 在上述回答中提到的,可以创建 Program.cs 的记录器。 However if this logger has to log in the logging providers configured on the WebApplicationBuilder, below line can be used但是,如果此记录器必须登录 WebApplicationBuilder 上配置的日志记录提供程序,则可以使用以下行

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

Are you not considering SeriLog ?你不考虑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. UseSerilog扩展很方便。 More on Logging here .更多关于日志在这里

A word of advice.一句忠告。 Don't use BuildServiceProvider . 不要使用 BuildServiceProvider It is a potential code smell.这是一种潜在的代码异味。

Added some reference links from the author of "ASP.Net core in action" book.添加了“ASP.Net core in action”一书作者的一些参考链接。

Disclaimer: I am not associated with Andrew Lock by any means though I would love to.免责声明:尽管我愿意,但我与Andrew Lock没有任何关系。 The man does write good articles on.Net.这个人确实在.Net 上写了好文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM