Rem San
Rem San

Reputation: 407

serilog to log only debug, error and warning logs but not information

I have an application with serilog configured for logging. I have a checkbox in my application, only on clicking that checkbox button it should log all information log else only Error and Warning log should be logged.

In debug mode how to log only Debug, error and warning log when the button is unchecked. I have been trying to do this since 2 days. I have tried all the ways suggested in google/stackoverflow using .MinimumLevel.Debug()/restrictedToMinimumLevel: LogEventLevel.Debug it did not work for me. It logs Information log as well.

Please help me on this. To log only Debug,error and warning log.

val is true when checkbox enabled:

if (val == "true")
{
    _logger = new LoggerConfiguration()
                    .MinimumLevel.Debug()
                    .WriteTo.File(_filepath, restrictedToMinimumLevel: LogEventLevel.Information)
                    .CreateLogger();
}
else if (val == "false")
{
    _logger = new LoggerConfiguration()
                    .MinimumLevel.Debug()
                    .WriteTo.File(_filepath, restrictedToMinimumLevel: LogEventLevel.Debug)
                    .CreateLogger();
}

when val is false, it.e., when check box is not enabled, it should log only debug,error and warning logs.

Upvotes: 5

Views: 5077

Answers (1)

ElasticCode
ElasticCode

Reputation: 7875

You cannot achieve it using MinimumLevelas @barbsan comment.

But you can use filtering for in your case.

Filters are just predicates over LogEvent

_logger  = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.File(_filepath)
    .Filter.ByIncludingOnly(isNotInfoLevel)
    .CreateLogger();

And in below function you can add more conditions if needed

private static bool isNotInfoLevel(LogEvent le)
{
    return le.Level != LogEventLevel.Information;
}

Anther way by using ByExcluding to exclude information level

.Filter.ByExcluding((le) => le.Level == LogEventLevel.Information)

Upvotes: 6

Related Questions