1
votes

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?

1

1 Answers

2
votes

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)