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

半城伤御伤魂 提交于 2020-01-05 01:01:30

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/55214337/serilog-to-log-only-debug-error-and-warning-logs-but-not-information

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!