[英]How to configure NLog programmatically for Async target?
I am trying to configure Nlog programmatically for use with async method.我正在尝试以编程方式配置 Nlog 以与异步方法一起使用。 However it seems that the documentation mostly provides examples for configuration using XML .
但是,文档似乎主要提供使用XML进行配置的示例。 A minimal example using code for an older NLog version is provided here .
此处提供了一个使用旧版 NLog 代码的最小示例。
I would like to do that by using NLog.Config.LoggingConfiguration()
, so here is how I proceeded:我想通过使用
NLog.Config.LoggingConfiguration()
来做到这一点,所以我是这样进行的:
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?我的问题如下:是否需要为
asyncFileTarget
创建单独的规则,或者是否足以为 fileTarget 添加规则?
It is important that the AddRule
references the AsyncWrapper, else it will write directly to the target without buffering. AddRule
引用 AsyncWrapper 很重要,否则它将直接写入目标而无需缓冲。
// 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
注意
AddRule
内部自动调用AddTarget
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.