简体   繁体   中英

How do I programmatically add logging filters?

I want to add the rule in my NLog. The rule is:

 <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>

Now I want to implement it in C# code. I haven't found the sample code online.

I would take a look a look at the Configuration API documentation for NLog. While it doesn't specifically reference filters, it seems like the way to accomplish this programmatically is by using LoggingRules to control how log messages are processed.

Edit

Like I said, the Configuration API is the way to achieve this. This example will replicate the following config programmatically:

Config

<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>

Code

// 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM