'How to configure NLog for Azure Functions?

I could really need some help.

I want to use NLog with Azure Functions v2 (Target Framework .NET Core 2.2) – and have created a

Startup : FunctionsStartup

class decorated with

[assembly: FunctionsStartup(typeof(PmsFunctions.Startup))]

And created this method

public override void Configure(IFunctionsHostBuilder builder)
{
    builder.Services.AddLogging(loggingBuilder =>
    {
        loggingBuilder.ClearProviders();
        loggingBuilder.SetMinimumLevel(LogLevel.Trace);
        loggingBuilder.AddNLog();
    }).BuildServiceProvider();
}

In constructor of the Startup class I have created the configuration of NLog using code:

var mailTarget = new MailTarget("mandrill")
{

    Html = true,
    AddNewLines = true,
    ReplaceNewlineWithBrTagInHtml = true,
    Subject = "XXXXX",
    To = "[email protected],
    From = "[email protected]",
    Body = "Message: ${message}${newline}${newline}Date: ${date}${newline}${newline}Exception: ${exception:format=tostring}${newline}${newline}",
    SmtpUserName = "XXXXXXX",
    SmtpPassword = "XXXXXXX",
    SmtpAuthentication = SmtpAuthenticationMode.Basic,
    SmtpServer = "XXXXXXXX",
    SmtpPort = 587
};

var bufferedMailTarget = new BufferingTargetWrapper("bufferedMandril", mailTarget)
{
    SlidingTimeout = false,
    BufferSize = 100,
    FlushTimeout = 10000
};
config.AddTarget(bufferedMailTarget);

var mailRule = new LoggingRule("*", NLog.LogLevel.Warn, bufferedMailTarget);
config.LoggingRules.Add(mailRule);

var logger = NLogBuilder.ConfigureNLog(config).GetCurrentClassLogger

I try to use the logger in the functons by using the injected ILogger. It works perfectly locally but it is completely “dead” when using Azure. I guess it is the way I configure the NLog.

How should I do it the right way?



Solution 1:[1]

To ensure NLog follows the lifetime of the Azure function, then you should configure it to shutdown (and flush) together with Microsoft-Extension-Logging:

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]

namespace MyNamespace
{
    public class Startup : FunctionsStartup
    {
        private readonly NLog.Logger Logger;

        public Startup()
        {
            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) =>
            {
                var nlogOptions = new NLogProviderOptions() {
                    ShutdownOnDispose = true, 
                    RemoveLoggerFactoryFilter = true
                };
                loggingBuilder.AddNLog(nlogOptions);
            });
        }
    }
}

Notice ShutdownOnDispose = true and AutoShutdown = false

Solution 2:[2]

I set mine up just like this and I'm successfully getting emails from my service in Azure (I set up one function to explicitly log a warning so when I call it, I get an email).

public Startup()
{
    LoggingConfiguration config = new LoggingConfiguration();

    var mailTarget = new MailTarget("mandrill")
    {
        Html = true,
        AddNewLines = true,
        ReplaceNewlineWithBrTagInHtml = true,
        Subject = "Test...",
        To = "-----",
        From = "[email protected]",
        Body = "Message: ${message}${newline}${newline}Date: ${date}${newline}${newline}Exception: ${exception:format=tostring}${newline}${newline}",
        SmtpUserName = "-----",
        SmtpPassword = "-----",
        SmtpAuthentication = SmtpAuthenticationMode.Basic,
        SmtpServer = "-----",
        SmtpPort = 587
    };

    var bufferedMailTarget = new BufferingTargetWrapper("bufferedMandril", mailTarget)
    {
        SlidingTimeout = false,
        BufferSize = 100,
        FlushTimeout = 10000
    };

    config.AddTarget(bufferedMailTarget);

    var mailRule = new LoggingRule("*", NLog.LogLevel.Warn, bufferedMailTarget);
    config.LoggingRules.Add(mailRule);

    NLogBuilder.ConfigureNLog(config);
}

public override void Configure(IFunctionsHostBuilder builder)
{
    builder.Services.AddLogging(b =>
    {
        b.AddNLog();
    });
}

Solution 3:[3]

Use MicrosoftILoggerTarget:

var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger);
loggerTarget.Layout = new NLog.Layouts.Layout("${message}${exception:format=tostring}");  // Can also be JsonLayout
var nlogConfig = new NLog.Config.LoggingConfiguration();
nlogConfig.AddRuleForAllLevels(loggerTarget);
NLog.LogManager.Configuration = nlogConfig;
var nlogLogger = NLog.LogManager.GetCurrentClassLogger();
nlogLogger.Info("Hello World");

Source: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-cloud-logging-with-Azure-function-or-AWS-lambda

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 brettsam
Solution 3 Jos van Egmond