= LogLevel.Debug and-6ren">
gpt4 book ai didi

c# - 如何以编程方式添加日志过滤器?

转载 作者:太空狗 更新时间:2023-10-30 00:40:07 24 4
gpt4 key购买 nike

我想在我的 NLog 中添加规则。规则是:

 <rules>
<logger name="*" writeTo="file">
<filters>
<when condition="length(message) > 100" action="Ignore" />
<when condition="equals('${logger}','MyApps.SomeClass')" action="Ignore" />
<when condition="(level >= LogLevel.Debug and contains(message,'PleaseDontLogThis')) or level==LogLevel.Warn" action="Ignore" />
<when condition="not starts-with('${message}','PleaseLogThis')" action="Ignore" />
</filters>
</logger>

现在我想用 C# 代码实现它。我没有在网上找到示例代码。

最佳答案

我会看一看 Configuration API NLog 的文档。虽然它没有具体引用过滤器,但似乎以编程方式完成此操作的方法是使用 LoggingRules 来控制如何处理日志消息。

编辑

正如我所说,配置 API 是实现这一目标的方式。此示例将以编程方式复制以下配置:

配置

<targets>            
<target name="console" type="Console" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="console">
<filters>
<when condition="not starts-with('${message})', 'PleaseLogThis')" action="Ignore" />
</filters>
</logger>
</rules>

代码

// Create the filter
var filter = new ConditionBasedFilter();
filter.Condition = "not starts-with('${message}','PleaseLogThis')";
filter.Action = FilterResult.Ignore;

// Create the rule to apply the filter to
var consoleTarget = new ColoredConsoleTarget();
var rule = new LoggingRule("*", LogLevel.Debug, consoleTarget);
rule.Filters.Add(filter);

// Create the config to apply the rule to
var config = new LoggingConfiguration();
config.LoggingRules.Add(rule);

// Update the log manager with the programmatic config
LogManager.Configuration = config;

// Test Your Logging
var log = LogManager.GetCurrentClassLogger();

log.Debug("Test");
log.Debug("Filter");
log.Debug("PleaseLogThis");

Console.ReadLine();

关于c# - 如何以编程方式添加日志过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30733574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com