Home > database >  Filter Azure function logs using NLog
Filter Azure function logs using NLog

Time:07-19

I'm trying to set up NLog to work with my Azure durable function (v4).

The NLog does configuration progromatically (not using config file) and writes to an Azure DB target via a sp.

It is working well in general. But there are lots of undesired logs both of debug and info level showing up in the DB along with my own user logs. They are the output of Azure service loggers like Azure.Core.1, DurableTask.AzureStorage, Host.xxx.

I tried several ways to filter them out:

  • adding items like "Azure.Core.1" : "Error" to the host.json file.
  • adding log filter like logBuilder.AddFilter("Azure.Core.1", Microsoft.Extensions.Logging.LogLevel.Error)
  • adding NLog rule like config.LoggingRules.Add(new LoggingRule("Azure.Core.1", NLog.LogLevel.Error, target));

But none of them works... Any advice, please?

CodePudding user response:

NLog evaluates the LoggingRules from top to bottom. This means global filters should be added first, and having the actual targets at the very end.

var myTarget = new AmazingNLogTarget();

var logger = LogManager.Setup().LoadConfiguration(c =>
{
   c.ForLogger("System.*").WriteToNil(NLog.LogLevel.Warn);
   c.ForLogger("Microsoft.*").WriteToNil(NLog.LogLevel.Warn);
   c.ForLogger("Microsoft.Hosting.Lifetime*").WriteToNil(NLog.LogLevel.Info);   // finalMinLevel overrides previous rule

   c.ForLogger().FilterMinLevel(NLog.LogLevel.Info).WriteTo(myTarget);
}).GetCurrentClassLogger();

See also: https://nlog-project.org/2021/08/25/nlog-5-0-preview1-ready.html#fluent-api-for-nlog-loggingconfiguration

  • Related