在调用 `builder.Build()` 之前在 `Main()` 中如何获取 `ILogger`?

huangapple go评论82阅读模式
英文:

How to get an ILogger in Main() before calling builder.Build()

问题

我按照这里这里的指导进行了操作。我得到的代码如下:

var configuration = new ConfigurationBuilder()
    .AddEnvironmentVariables()
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
    true, true)
    .Build();
using (var loggerFactory = LoggerFactory.Create(loggingBuilder => loggingBuilder
           .AddConfiguration(configuration)))
{
    logger = loggerFactory.CreateLogger<Program>();
}

这给我一个有效的ILogger,但没有生成日志。我查看了配置对象,它包含了我在appsettings.development.json中的所有设置。

所以,我接着做了以下操作:

using (var loggerFactory = LoggerFactory.Create(loggingBuilder => loggingBuilder
           .AddConfiguration(configuration.GetSection("Logging"))
           .AddJsonConsole()
           .AddDebug()))
{
    logger = loggerFactory.CreateLogger<Program>();
}

这样就可以正常工作了。如果没有.GetSection("Logging"),它只会显示警告级别及更高级别的日志。如果没有AddJsonConsole()AddDebug(),它什么日志都不显示。

那么...为什么会这样呢?虽然现在已经能正常工作,但我想知道为什么它不能直接从配置中构建?

英文:

I followed the guidance here and here. And what I came up with is:

	var configuration = new ConfigurationBuilder()
			.AddEnvironmentVariables()
			.AddJsonFile($&quot;appsettings.{Environment.GetEnvironmentVariable(&quot;ASPNETCORE_ENVIRONMENT&quot;)}.json&quot;,
			true, true)
			.Build();
		using (var loggerFactory = LoggerFactory.Create(loggingBuilder =&gt; loggingBuilder
				   .AddConfiguration(configuration)))
		{
			logger = loggerFactory.CreateLogger&lt;Program&gt;();
		}

That gave me a valid ILogger - that generated no logs. I did look at the configuration object and it did have all the settings from my appsettings.development.json.

So I then did the following:

		using (var loggerFactory = LoggerFactory.Create(loggingBuilder =&gt; loggingBuilder
				   .AddConfiguration(configuration.GetSection(&quot;Logging&quot;))
				   .AddJsonConsole()
				   .AddDebug()))
		{
			logger = loggerFactory.CreateLogger&lt;Program&gt;();
		}

And this works. Without the .GetSection(&quot;Logging&quot;) it only displayed logs of Warning and greater. Without the AddJsonConsole() and AddDebug() it displayed nothing.

So... why? I have it working and that's great, but I'd like to know why it doesn't build from the config?

答案1

得分: 0

appsettings中的配置只是将值设置为日志系统中使用的值。

但是,您仍然需要使用AddJsonConsole和AddDebug来实际添加提供程序到日志系统中。然后,appsettings中的配置将对其进行配置。

没有显式添加提供程序的配置将使配置变得多余。

英文:

The config in appsettings is just setting value to be used with the logging system.

However, you still require AddJsonConsole and AddDebug to actually add the providers to the logging system. The configuration in appsettings will then configure those.

The configuration without explicitly adding the providers will render the configuration redundant.

答案2

得分: 0

这里是相关的文档

默认的ASP.NET Core Web应用程序模板:

使用通用主机。调用WebApplication.CreateBuilder,它会添加以下日志提供程序:

控制台

调试

EventSource

EventLog:仅限Windows

您还可以在WebApplicationBuilder中检查代码:

services.AddLogging(logging =>
{
    logging.AddConfiguration(configuration.GetSection("Logging"));
    logging.AddSimpleConsole();

    logging.Configure(options =>
    {
        options.ActivityTrackingOptions =
            ActivityTrackingOptions.SpanId |
            ActivityTrackingOptions.TraceId |
            ActivityTrackingOptions.ParentId;
    });
});

它已经为您执行了创建ILogger时必须执行的操作,但是当您通过ILoggerFactory创建ILogger时,您需要自己设置提供程序和配置。

英文:

Here's the document related:

> The default ASP.NET Core web app templates:
>
> Use the Generic Host. Call WebApplication.CreateBuilder, which adds
> the following logging providers:
>
> Console
>
> Debug
>
> EventSource
>
> EventLog: Windows only

You could also check the codes in WebApplicationBuilder

services.AddLogging(logging =&gt;
        {
            logging.AddConfiguration(configuration.GetSection(&quot;Logging&quot;));
            logging.AddSimpleConsole();

            logging.Configure(options =&gt;
            {
                options.ActivityTrackingOptions =
                    ActivityTrackingOptions.SpanId |
                    ActivityTrackingOptions.TraceId |
                    ActivityTrackingOptions.ParentId;
            });
        });

It has already did what you have to do for you ,when you create Ilogger through Iloggerfactory ,you have to set the provider and configuration yourself

huangapple
  • 本文由 发表于 2023年8月4日 02:20:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830703.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定