简体   繁体   中英

Dispose NLog in Azure Function

I want to add NLog in Azure Functions Startup class like below:

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();
        });
    }
}

According to Nlog, you should manually shutdown the logger using NLog.LogManager.Shutdown() . How to dispose NLog in Azure Function?

If I understand your question correctly, you want to Shutdown NLog when Azure Function instance gets disposed. In this case, you can do something like below:

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 });
        });
    }
}

Now NLog will hook into the lifetime of Microsoft Extension Logging (Disabling AutoShutdown and enable ShutdownOnDispose )

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