【问题标题】:NLog Custom Target fails in Azure .NET Core 2.1NLog 自定义目标在 Azure .NET Core 2.1 中失败
【发布时间】:2018-06-27 10:31:52
【问题描述】:

一段时间以来,我一直在使用 NLog 与 .NET Core 2.0 和自定义目标来成功写入 Azure Blob 存储。

我现在已经升级到 .NET Core 2.1,但部署到 Azure Web 应用程序的解决方案失败了,因为根据 Kudu 事件日志,NLog 找不到 NLog 配置文件中定义的自定义目标,虽然它似乎在本地工作得很好。

我的主机生成器如下:

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseUnityServiceProvider()
            .UseNLog()
            .UseStartup<Startup>();

而我的 NLog 目标是在启动类中定义的:

        public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", false, true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
            .AddJsonFile("appsettings.local.json", true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();
        HostingEnvironment = env;

        NLogRegistry.Register(env, new ConfigurationAdapter(Configuration));
    }

NLog Registry 只是基于Custom target with injected services for NLog with .net core 的解决方案的包装器

即

    public class NLogRegistry
{
    public static void Register(IHostingEnvironment env, IConfigurationAdapter configuration)
    {
        //Setup custom NLog Azure Blob logger with injected configuration
        Target.Register<AzureBlobStorageTarget>("AzureBlobStorage");

        var nlog = ConfigurationItemFactory.Default.CreateInstance;
        ConfigurationItemFactory.Default.CreateInstance = type =>
        {
            try
            {
                return nlog(type);
            }
            catch (Exception)
            {
            }

            return new AzureBlobStorageTarget(configuration);
        };

        env.ConfigureNLog("nlog.config");
    }
}

我认为正在发生的事情是 .NET Core 管道的行为发生了一些变化,因此 NLog 在 Startup 方法之前被调用。由于 NLog 被配置为“自动发现”nlog.config,它会在我有机会正确配置目标之前尝试设置。

如果我重命名 nlog.config 文件,那么自动发现不会发生,NLog 必须等到我在我的注册类中运行 ConfigureNLog 方法。然后,一切正常。

有谁知道 Azure 调用的 ASP.NET Core 2.1 管道中的正确位置是确保我可以在 NLog 尝试自动配置之前正确配置 NLog 目标?

【问题讨论】:

  • NLog 尝试在您创建第一个 Logger 对象后立即对其进行配置(还包括类初始化时的静态 Logger 对象)。也许一些依赖注入框架正在触发一些静态类初始化器?
  • @RolfKristensen 我想这是有道理的,我想知道 .NET Core 2.1 管道中发生了什么变化来调用它。

标签: azure nlog asp.net-core-2.1


【解决方案1】:

您现在可以将 NLog Layout-Type 用于 AzureBlobStorageTarget-properties,而不是将 IConfiguration 在构造函数中注入到您的 AzureBlobStorageTarget。

然后使用 NLog.Extension.Logging 版本引入的${configsetting} 配置布局。 1.4.0:

https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer

也许也可以考虑改为这个 NLog-target:

https://github.com/JDetmar/NLog.Extensions.AzureStorage#blob-configuration

但是如果你坚持使用依赖于构造函数参数的依赖注入的自定义目标:

https://github.com/NLog/NLog/wiki/Dependency-injection-with-NLog

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2014-03-25
    • 2018-06-19
    相关资源
    最近更新 更多