首页 > 解决方案 > 启动期间加载记录器配置需要很长时间

问题描述

最近我将项目从 2.2 迁移到 AspNetCore 3.1,并开始使用 Visual Studio 2019。从那时起,启动应用程序大约需要一分钟。大部分时间应用程序正在获取 nlog.config:

 public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        Configuration = configuration;
        LogManager.LoadConfiguration(System.String.Concat
(Directory.GetCurrentDirectory(), "/nlog.config")); //here's where it hangs

        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            //.AddJsonFile($"rabbitConfig.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();
    }

我知道 IHostingEnvironment 已经过时了,它会导致这个问题吗?我应该改变什么以使其加载更快?

标签: c#asp.net-corenlogasp.net-core-3.1

解决方案


如果您的同事没有遇到问题,那么您很可能是 Visual Studio 2019 中可笑的缓慢符号加载的受害者。一种解决方法是启用仅我的代码

您可以尝试跳过对程序集的自动扫描以加载 NLog 扩展:

public Startup(IConfiguration configuration, IHostingEnvironment env)
{
   Configuration = configuration;

   //disable NLog assembly scanning
   NLog.Config.ConfigurationItemFactory.Default = new NLog.Config.ConfigurationItemFactory(typeof(NLog.ILogger).GetTypeInfo().Assembly);

   //here's where it hangs
   NLog.LogManager.LoadConfiguration(System.String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));

    ...
}

还推荐使用 NLog 4.6.8,因为它有一些优化来加快配置加载。

请注意,如果您在 Trace-Level 上启用了 NLog InternalLogger,那么它也会损害性能。

请记住,如果您禁用默认的 MEL-Console-Logger,或从Microsoft.Hosting.Lifetime-Logger 中过滤掉 Info-Level-messages,则托管环境将超时等待预期的启动消息。确保配置 NLog-Console-output 或保留 AddConsole-output:

https://github.com/NLog/NLog.Web/wiki/Hosting-Lifetime-Startup-Messages

在 ASP.NET Core 2 中,它会直接写入控制台,但在 ASP.NET Core 3 中,它使用调用的 MEL-ILogger Microsoft.Hosting.Lifetime(请记住在 ASP.NET Core 中配置 MEL-Filter 和 NLog-Filter 以不丢弃这些消息3)


推荐阅读