My question is very similar to this one: How can I get NLog output to appear in the streaming logs for an Azure Function?. In that question the accepted answer shows how you can configure nlog at the start of the function call. I would like to configure via an nlog.config file or at the very least configure just once at setup and not on every call to the function.
With the code below I see NLog messages in the Application Insight logs, but not in the Log Stream. I would like to get the messages logged from NLog to show in Log Streams as well.
Function code
private static readonly Logger _logger = NLog.LogManager.GetCurrentClassLogger();
[FunctionName("TestLog")]
public static async Task<IActionResult> TestLog([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
HttpRequest req, ILogger log)
{
//shows in both Application Insights and Log Stream.
log.LogInformation("Log From ILogger");
//shows in Application Insights but not in Log Stream.
_logger.Info("Log From NLog");
return new OkObjectResult("OK");
}
FunctionStartUp
[assembly: FunctionsStartup(typeof(MyNamespace.TestFunctionApp.Startup))]
namespace MyNamespace.TestFunctionApp
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
//nLog file ends 1 directory up from bins when deployed
var binDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var rootDirectory = Path.GetFullPath(Path.Combine(binDirectory, ".."));
var nLogConfigPath = Path.Combine(rootDirectory, "NLog.config");
//create MicrosoftILoggerTarget (I think this has to be done from code since it needs a ref to an ILogger instance). But this does not seem to work.
var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
var azureILogger = loggerFactory.CreateLogger("NLog");
var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger);
//setup NLog
LogManager.Setup()
.SetupExtensions(e => e.AutoLoadAssemblies(false))
.LoadConfigurationFromFile(nLogConfigPath, optional: false)
.LoadConfiguration(builder => builder.Configuration.AddRuleForAllLevels(loggerTarget));
}
}
}
NLog.config
<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<extensions>
<add assembly="Microsoft.ApplicationInsights.NLogTarget" />
</extensions>
<targets>
<target name="a" xsi:type="ApplicationInsightsTarget"/>
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="a" />
</rules>
</nlog>