NeilMacMullen
NeilMacMullen

Reputation: 3467

How can I get NLog output to appear in the streaming logs for an Azure Function?

I have a simple Azure Function and I'd like to be able to monitor log output in both the streaming log window and in Application Insights.

So far I am able to see NLog output in Application Insights but not in the streaming window. Microsoft ILogger output appears in both.

Here's what I've done so far:

So far, the results are that:

Here is the final function code...

public static class Function1
{
    [FunctionName("LogTest")]
    public static void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log)
    {
        // Set up NLOG targets and logger
        var config = new LoggingConfiguration();
        //send logging to application insights     
        config.LoggingRules.Add(
          new LoggingRule("*", LogLevel.Trace, 
          new ApplicationInsightsTarget()));
        //also try to log to Trace output 
        //'RawWrite' is used to try and force output at all log-levels  
        config.LoggingRules.Add(
          new LoggingRule("*", LogLevel.Trace, 
          new TraceTarget {RawWrite = true}));

        LogManager.Configuration = config;
        var nlog = LogManager.GetLogger("Example");

        //log using native
        log.LogInformation($"log:Info"); //appears in live-stream, app-insights
        log.LogError("log:Error");       //appears in live-stream, app-insights
        log.LogTrace("log:Trace");       //appears in live-stream, app-insights (after modifying host.json)

        //log using nlog
        nlog.Info("nlog:info");          //appears in ...........  app-insights
        nlog.Error("nlog:error");        //appears in ...........  app-insights
        nlog.Trace("nlog:trace");        //appears in ...........  app-insights                     

        //say goodbye
        log.LogInformation("log:ending");
    }
}

Thanks in advance for any suggestions - no doubt I'm missing some simple step.

Upvotes: 2

Views: 1913

Answers (1)

NeilMacMullen
NeilMacMullen

Reputation: 3467

Thanks to the link provided by Rolf Kristensen
it seems the solution is to configure a new rule using the MicrosoftILoggerTarget rather than the TraceTarget.

So the complete code is

var config = new LoggingConfiguration();
//ensure that log output is seen in the Streamed Log window
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, 
     new MicrosoftILoggerTarget(azureLog)));
//ensure that log output is sent to Application Insights
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, 
     new ApplicationInsightsTarget()));
LogManager.Configuration = config;
var nlog = LogManager.GetLogger("Example");
nlog.Info("output from nlog");

where azureLog is the ILogger provided to the Run method of the function.

MicrosoftILoggerTarget can be found in the NLog.Extensions.Logging nuget package.

Upvotes: 4

Related Questions