The correct way to ignore log entries with NLog at runtime

Will Calderwood

I create a MongoTarget at runtime to the server that's hosting the production database. What's the correct way to ignore unwanted log entries at runtime? I'm currently creating a MemoryTarget and creating a rule to send the unwanted log entries to that with Final = true, which works but feels pretty hacky. What should I be doing?

    var memoryTarget = new MemoryTarget
    {
        Name = "memory",
        MaxLogsCount = 100
    };

    var rule = new LoggingRule("Microsoft.*", LogLevel.Trace, LogLevel.Info, memoryTarget) { Final = true };
    config.LoggingRules.Add(rule);

I've tried adding a ConditionBasedFilter, but this seems to ignore everything.

    rule.Filters.Add(new ConditionBasedFilter()
    {
        Condition = "starts-with(logger, 'Microsoft')",
        Action = FilterResult.Ignore
    });            

Complete Code With Answer From Rolf

    private void SetUpLogging(string connectionString)
    {
        var mongoTarget = new MongoTarget
        {
            Name = "mongolog",
            ConnectionString = connectionString,
            CollectionName = "ApiLog",
            IncludeDefaults = true,
            IncludeEventProperties = true,
            DatabaseName = "Log",
            CappedCollectionSize = 20000000
        };

        LogManager.Setup().LoadConfiguration(c =>
        {
            c.ForLogger("Microsoft.*").WriteToNil(LogLevel.Warn); 
            c.ForLogger().FilterMinLevel(LogLevel.Debug).WriteTo(mongoTarget);
        });
    } 
Rolf Kristensen

NLog v5 allows you to do this:

LogManager.Setup().LoadConfiguration(c =>
{
   c.ForLogger("Microsoft.*").WriteToNil(LogLevel.Warn); // FinalMinLevel
   c.ForLogger().FilterMinLevel(LogLevel.Info).WriteTo(mongoTarget);
});

See also: https://github.com/NLog/NLog/wiki/Fluent-Configuration-API

See also: https://github.com/NLog/NLog/wiki/Logging-Rules-FinalMinLevel

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related