NLog自定义目标在Azure .NET Core 2.1中失败

时间:2018-06-27 10:31:53

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

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

我现在已升级到.NET Core 2.1,并且部署到Azure Web App的解决方案失败,因为根据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注册表只是基于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。由于NLog被配置为“自动发现” nlog.config,因此它会在我有机会正确配置目标之前尝试进行设置。

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

有人知道Azure在ASP.NET Core 2.1管道中的正确位置是什么,以确保在NLog尝试自动配置其自身之前,我可以正确配置NLog目标吗?

1 个答案:

答案 0 :(得分:0)

您现在可以仅将NLog Layout-Type用于AzureBlobStorageTarget属性,而不必在构造函数中向{BetaStorageTarget中注入IConfiguration

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

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

也许也可以考虑改为使用此NLog目标:

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

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

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