简体   繁体   中英

How to shutdown NLog logging in an Azure Function?

I need to setup NLog when Azure Functions instantiates my assembly.

public class Startup : FunctionsStartup {
    public Startup()
    {        
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    }
    public override void Configure(IFunctionsHostBuilder builder) {
        ... other setup code
        builder.Services.AddLogging((loggingBuilder) =>
        {
            loggingBuilder.AddNLog();
        });
    }
}

NLog folks recommend manually shutting down the logger via NLog.LogManager.Shutdown() . The problem is that I am not sure how to catch the instance of Azure shutting my assembly down.

Does Azure expose a Dispose event of some sort that I am not seeing?

Looks like you are depending on Microsoft Extension Logging, so I would probably hook into its lifetime-logic (Disable AutoShutdown and enable ShutdownOnDispose )

public class Startup : FunctionsStartup {
    public Startup()
    {
        var logger = LogManager.Setup()
           .SetupExtensions(e => e.AutoLoadAssemblies(false))
           .LoadConfigurationFromFile("nlog.config", optional: false)
           .LoadConfiguration(builder => builder.LogFactory.AutoShutdown = false)
           .GetCurrentClassLogger();
    }

    public override void Configure(IFunctionsHostBuilder builder) {
        ... other setup code
        builder.Services.AddLogging((loggingBuilder) =>
        {
            loggingBuilder.AddNLog(new NLogProviderOptions() { ShutdownOnDispose = true });
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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