简体   繁体   中英

Nlog in Azure functions not working when injected via DI

Reference Code taken from https://stackoverflow.com/questions/56512672/how-to-configure-nlog-for-azure-functions#:~:text=0,and%20AutoShutdown%20%3D%20false

My StartUp.cs file

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 function file"

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>

Code with "This is printing" is working fine but when injecting from DI it is not printing logs. Some default logs are getting printed but not with log.LogInformation.

host.json is empty, no logging configs are there which are provided by default.

Could someone please help. Searched many where but could not find the reason. GitHub repo link - https://github.com/jatingandhi28/NLogAzureFunctions

You can try to disable the filter-logic in Microsoft LoggerFactory by changing from:

new NLogProviderOptions() { ShutdownOnDispose = true }

To this

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

See also: https://github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-6%3F

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM