How do I programmatically add registration filters?

I want to add a rule to my NLog. Rule:

 <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 any sample code online.

+3


source to share


1 answer


I would like to take a look at the documentation for the Configuration API for NLog. Even though it doesn't specifically refer to filters, it seems like the way to do it programmatically is to use it LoggingRules

to control the handling of log messages.

Edit

As I said, the config API is the way to achieve this. In this example, the code will be replicated 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();

      

+5


source







All Articles