Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add, enable and disable NLog loggers programmatically

Tags:

How can I add, edit, delete, enable, and disable loggers from code for NLog?

like image 897
Stacker Avatar asked Sep 19 '11 13:09

Stacker


People also ask

Is NLog asynchronous?

NLog 1.0 supports asynchronous logging, but there is no good support for asynchronous exception handling. This is because wrappers targets are not capable of receiving exceptions which are raised on other threads.

What is NLog config in C#?

NLog is a . Net Library that enables you to add high-quality logs for your application. NLog can also be downloaded using Nugget in Visual Studio. Targets are used to display, store, or pass log messages to another destination.


2 Answers

I know this is an old answer but I wanted give feedback for anyone looking to make modifications to their targets and logging rules programmatically that Configuration.Reload() doesn't work.

To update existing targets programmatically you need to use the ReconfigExistingLoggers method:

var target = (FileTarget)LogManager.Configuration.FindTargetByName("logfile");
target.FileName = "${logDirectory}/file2.txt";
LogManager.ReconfigExistingLoggers();

An example that adds and removes logging rules on the fly:

if (VerboseLogging && !LogManager.Configuration.LoggingRules.Contains(VerboseLoggingRule))
{
    LogManager.Configuration.LoggingRules.Add(VerboseLoggingRule);
    LogManager.ReconfigExistingLoggers();
}
else if (!VerboseLogging && LogManager.Configuration.LoggingRules.Contains(VerboseLoggingRule))
{
    LogManager.Configuration.LoggingRules.Remove(VerboseLoggingRule);
    LogManager.ReconfigExistingLoggers();
}

As written in docs:

Loops through all loggers previously returned by GetLogger. and recalculates their target and filter list. Useful after modifying the configuration programmatically to ensure that all loggers have been properly configured.

This answer and sample comes from Tony's answer in:

Update NLog target filename at runtime

like image 22
Neil Bostrom Avatar answered Sep 18 '22 12:09

Neil Bostrom


To add:

var logTarget = new ...
logTarget.Layout = "Your layout format here";
// e.g. "${logger}: ${message} ${exception:format=tostring}";

// specify what gets logged to the above target
var loggingRule = new LoggingRule("*", LogLevel.Debug, logTarget);

// add target and rule to configuration
LogManager.Configuration.AddTarget("targetName", logTarget);
LogManager.Configuration.LoggingRules.Add(loggingRule);
LogManager.Configuration.Reload();

Removal is done with

LogManager.Configuration.LoggingRules.Remove(loggingRule);
LogManager.Configuration.Reload();
like image 77
Jon Avatar answered Sep 21 '22 12:09

Jon