通过 DI 注入时,Azure 中的 Nlog 函数不起作用

Nlog in Azure functions not working when injected via DI

参考代码取自

我的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>

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

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

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

您可以尝试通过更改以下内容来禁用 Microsoft LoggerFactory 中的 filter-logic:

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