1

Let's say I have this partial configuration, with NLog:

<rules>
   <logger name="ExistsInConfig" writeTo="Console"/>
</rules>

..and then I write this code:

var configuredLogger = LogManager.GetLogger("ExistsInConfig");
configuredLogger.Log(LogLevel.Info, "hello, cruel world!");

var missingLogger = LogManager.GetLogger("NotInConfig");
missingLogger.Log(LogLevel.Info, "goodbye, cruel world!");

In the console output I will see only the first logging statement, because the second named logger was not found in the config file.

How can I programatically detect that the second logger was not found, and therefore will produce no output?

Julian
  • 33,915
  • 22
  • 119
  • 174
badlife
  • 23
  • 4

2 Answers2

1

If you have the instance of Logger, you could ask it to it:

bool hasConfigRuleForInfo = missingLogger.IsEnabled(LogLevel.Info)

If not, then you need some tricks, some possibilities:

  • or create your own LogManager class remember which remembers which loggers are used
  • or read with reflection the private propertiy LogManager.factory.loggerCache (not supported of course ;))
  • add a wildcard( *) rule to your config (API or XML) and write to MemoryTarget or a Custom Target. This could effect your performance. PS. with ${logger} you get the logger name. You will also need the final option on other rules.
Julian
  • 33,915
  • 22
  • 119
  • 174
  • Thanks for the advice! I will have the instance of the logger, but checking .IsEnabled(LogLevel) could fail if a named logger is found but just doesn't happen to have logging enabled for that level.. I had considered going this route and looking to see if the logger is enabled for *all* levels, but even then it would be possible for someone to deliberately (and legitimately) configure a logger that way.. – badlife Apr 08 '17 at 18:44
  • is this working for you? Accepted / up-vote allowed ;) – Julian Apr 16 '17 at 13:35
  • I'm too new to be allowed to accept an answer or up-vote. When I click the up-vote I'm told it's recorded but won't be displayed. – badlife Apr 18 '17 at 15:19
1

I think this is the best way:

if (!NLog.LogManager.Configuration.ConfiguredNamedTargets.Any(t => t.Name.Equals("NameToValidate")))
{ 
//config not found 
}

With @Julian 's answer, you could have the Config you are looking for but not the level you are comparing within. You could even have the Config without any level activated in your NLog config.

In those cases you would get an incorrect check response.

LMes86
  • 11
  • 4