【发布时间】:2021-02-24 19:17:27
【问题描述】:
我的问题与这个问题非常相似:How can I get NLog output to appear in the streaming logs for an Azure Function?。在那个问题中,接受的答案显示了如何在函数调用开始时配置 nlog。我想通过 nlog.config 文件进行配置,或者至少在设置时配置一次,而不是在每次调用该函数时配置一次。
使用下面的代码,我在 Application Insight 日志中看到 NLog 消息,但在日志流中看不到。我希望从 NLog 记录的消息也显示在 Log Streams 中。
功能代码
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");
}
函数启动
[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>
【问题讨论】:
标签: azure azure-functions nlog