【问题标题】:Nlog in Azure functions not working when injected via DI通过 DI 注入时 Azure 函数中的 Nlog 不起作用
【发布时间】:2022-02-10 01:53:01
【问题描述】:

参考代码取自https://stackoverflow.com/questions/56512672/how-to-configure-nlog-for-azure-functions#:~:text=0,and%20AutoShutdown%20%3D%20false

我的 StartUp.cs 文件

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using NLog.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

[assembly: FunctionsStartup(typeof(NLogFunctionApp.StartUp))]
namespace NLogFunctionApp
{
    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 hostBuilder)
        {
            hostBuilder.Services.AddLogging((loggingBuilder) =>
            {
                loggingBuilder.AddNLog(new NLogProviderOptions() { ShutdownOnDispose = true });
            });
        }
    }
}

“NLogSample.cs 函数文件”

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using NLog;

namespace NLogFunctionApp
{
    public class NLogSample
    {
        private readonly ILogger<NLogSample> log;
        private static  Logger logCurrent;

        public NLogSample(ILogger<NLogSample> logger)
        {
            log = logger;
            logCurrent = LogManager.GetCurrentClassLogger();
        }

        [FunctionName("NLogSample")]
        public void Run([TimerTrigger("0 * * * * *")]TimerInfo myTimer)
        {
            logCurrent.Info("This is printing");
            log.LogInformation("This is not printing");
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        }
    }
}

nlog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="https://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="c:\temp\jjgnet-functions-internal-nlog.log"
      internalLogLevel="Debug" >

  <variable name="logDirectory" value="${currentdir}${dir-separator}logs${dir-separator}" />
  <extensions>
    <add assembly="NLog.Extensions.Logging"/>
    <add assembly="Microsoft.ApplicationInsights.NLogTarget" />
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!--<target xsi:type="File" name="file-everything" fileName="${logDirectory}${shortdate}-everything.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${gdc:item=Version}|${message} ${exception:format=tostring}" />
    <target xsi:type="File" name="file-host" fileName="${logDirectory}${shortdate}-host.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${gdc:item=Version}|${message} ${exception:format=tostring}" />
    <target xsi:type="File" name="file-just-mine" fileName="${logDirectory}${shortdate}-just-mine.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${gdc:item=Version}|${message} ${exception:format=tostring}" />-->

    <target xsi:type="ApplicationInsightsTarget" name="aiTarget">
      <instrumentationKey>AzureAppInsightkeyvalue</instrumentationKey>
      <!-- Only required if not using ApplicationInsights.config -->
      <contextproperty name="threadid" layout="${threadid}" />
      <contextproperty name="AssemblyVersion" layout="${gdc:item=ExecutingAssembly-AssemblyVersion}" />
      <contextproperty name="FileVersion" layout="${gdc:item=ExecutingAssembly-FileVersion}" />
      <contextproperty name="ProductVersion" layout="${gdc:item=ExecutingAssembly-ProductVersion}" />
    </target>

    <target xsi:type="Console" name="logconsole"
            layout="${longdate}|${level}|${logger}|${message} |${all-event-properties} ${exception:format=tostring}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <logger name="*" minlevel="Trace" writeTo="logconsole" />
    <logger name="*" minlevel="Trace" writeTo="aiTarget" />
  </rules>
</nlog>

带有“正在打印”的代码工作正常,但从 DI 注入时它不打印日志。 一些默认日志正在打印,但 log.LogInformation 没有。

host.json 为空,没有默认提供的日志记录配置。

有人可以帮忙吗?找了很多地方都找不到原因。 GitHub 回购链接 - https://github.com/jatingandhi28/NLogAzureFunctions

【问题讨论】:

  • 如果将LogInformation 更改为LogError 会发生什么?
  • @RolfKristensen - 感谢您的回复,检查但无济于事。添加了 github repo 链接。
  • 如果将new NLogProviderOptions() { ShutdownOnDispose = true } 替换为new NLogProviderOptions() { ShutdownOnDispose = true, RemoveLoggerFactoryFilter = true } 会发生什么
  • @RolfKristensen 工作就像魅力!你是一颗宝石!添加 ApplicationInsightsTarget 时我面临的另一个问题 - 它没有登录 Azure ApplicationInsights?请在答案中发布,我会接受的。
  • @RolfKristensen 现在 AppInsights 也能完美运行。谢谢你的快速帮助。如果有人需要帮助,我会更新 Git 仓库上的代码。

标签: azure-functions nlog


【解决方案1】:

您可以尝试通过更改以下内容来禁用 Microsoft LoggerFactory 中的过滤逻辑:

new NLogProviderOptions() { ShutdownOnDispose = true }

到这里

new NLogProviderOptions() { ShutdownOnDispose = true, RemoveLoggerFactoryFilter = true }

另请参阅:https://github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-6%3F

【讨论】:

  • 您提供的github链接正在添加配置。就我而言,我有 Azure 功能,如果我在 host.json 中添加此配置,则默认日志记录将启动并打印两个日志。我找不到删除此日志记录的方法,ClearProviders 在 Azure 函数中引发错误。我无法理解这些配置?
  • @JatinGandhi 我只是想强调 Microsoft LoggerFactory 具有内置过滤功能。不是如何控制 Azure-Functions 过滤的专家。除此之外,还可以使用RemoveLoggerFactoryFilter 关闭 NLog 过滤。
猜你喜欢
  • 2020-12-10
  • 2013-03-22
  • 1970-01-01
  • 2019-12-18
  • 2015-08-17
  • 2018-09-11
  • 2013-08-07
  • 2020-05-29
  • 1970-01-01
相关资源
最近更新 更多