I am trying to configure Nlog programmatically for use with async method. However it seems that the documentation mostly provides examples for configuration using XML. A minimal example using code for an older NLog version is provided here.
I would like to do that by using NLog.Config.LoggingConfiguration()
, so here is how I proceeded:
var config = new NLog.Config.LoggingConfiguration();
// Targets:
NLog.Targets.FileTarget fileTarget = new NLog.Targets.FileTarget("fileTarget")
{
FileName = "\\MyLogFileDirectory.txt",
ArchiveAboveSize = 25000000,
MaxArchiveFiles = 10
};
//Handle Async:
NLog.Targets.Wrappers.AsyncTargetWrapper asyncFileTarget = new NLog.Targets.Wrappers.AsyncTargetWrapper(fileTarget)
{
Name = fileTarget.Name,
QueueLimit = 10,
OverflowAction = NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Discard
};
config.AddTarget(asyncFileTarget);
// Rules:
config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget, "MyLog");
NLog.LogManager.Configuration = config;
EDITS:
My question is the following:
Does a separate Rule needs to be created for asyncFileTarget
or is it enough to add the rule for fileTarget ?
It is important that the AddRule
references the AsyncWrapper, else it will write directly to the target without buffering.
// Apply Async
NLog.Targets.Wrappers.AsyncTargetWrapper asyncFileTarget = new NLog.Targets.Wrappers.AsyncTargetWrapper(fileTarget)
{
Name = fileTarget.Name,
QueueLimit = 10,
OverflowAction = NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Discard
};
// WriteTo Async
config.AddRule(LogLevel.Info, LogLevel.Fatal, asyncFileTarget, "MyLog");
Notice that AddRule
internally automatically calls AddTarget