gpt4 book ai didi

azure - 使用 nlog.config 在 Azure Function Log Streams 中进行 NLog

转载 作者:行者123 更新时间:2023-12-03 04:56:59 28 4
gpt4 key购买 nike

我的问题与此非常相似:How can I get NLog output to appear in the streaming logs for an Azure Function? 。在该问题中,接受的答案显示了如何在函数调用开始时配置 nlog。我想通过 nlog.config 文件进行配置,或者至少在设置时仅配置一次,而不是每次调用该函数时都配置一次。

使用下面的代码,我在 Application Insight 日志中看到 NLog 消息,但在日志流中看不到。我希望从 NLog 记录的消息也显示在日志流中。

函数代码

    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>

最佳答案

通常目标是让 Microsoft ILogger 的输出达到 NLog 目标。这是通过调用 UseNLog()AddNLog() 来完成的,这会将 NLog 添加为 LoggingProvider。

替代方案有一个已使用 NLog 的现有库,但希望将输出重定向到 Microsoft ILoggerFactory。但如果还想添加 NLog 作为 LoggingProvider,则必须小心,因为这是循环/递归的噩梦。

但我想您可以执行以下操作将所有输出从 NLog 重定向到 Microsoft ILoggerFactory:

    public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var serviceProvider = builder.Services.BuildServiceProvider();
var executionContextOptions = serviceProvider.GetService<IOptions<ExecutionContextOptions>>().Value;
var appDirectory = executionContextOptions.AppDirectory;

var loggerFactory = serviceProvider.GetService<ILoggerFactory>();

// Setup NLog redirect all logevents to Microsoft ILoggerFactory
var nlogLoggerName = "NLog";
var nlogLogger = loggerFactory.CreateLogger(nlogLoggerName);
var nlogTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(nlogLogger);
var nLogConfigPath = Path.Combine(appDirectory, "NLog.config");

//setup NLog
LogManager.Setup()
.SetupExtensions(e => e.AutoLoadAssemblies(false))
.LoadConfigurationFromFile(nLogConfigPath, optional: false)
.LoadConfiguration(builder => {
// Ignore output from logger named "NLog" to avoid recursion
builder.Configuration.Rules.Add(new LoggingRule() { LoggerNamePattern = nlogLoggerName, MaxLevel = LogLevel.Off, Final = true });
builder.Configuration.AddRuleForAllLevels(loggerTarget));
});
}
}

关于azure - 使用 nlog.config 在 Azure Function Log Streams 中进行 NLog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66357471/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com