ILogger(ASP.NET Core)日志甚至被称为IsEnabled返回false [英] ILogger (ASP.NET Core) Log is called even IsEnabled return false

查看:192
本文介绍了ILogger(ASP.NET Core)日志甚至被称为IsEnabled返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解 IsEnabled 方法.我希望每次可以记录日志时都会自动调用该方法,但是无论返回什么IsEnabled,都不会调用Log方法.

I am trying to understand the purpose of IsEnabled method in ILogger interface. I would expect that method is automatically called every time something can be log, but method Log is called no mater what returned IsEnabled.

我应该在Log方法中检查IsEnabled吗?

Should I check IsEnabled inside Log method?

    public bool IsEnabled(LogLevel logLevel)
    {
        return logLevel >= this.level;
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        if (this.IsEnabled(logLevel))   //it seams that this is required ????
        {
            string s = formatter(state, exception);
            string formatted = s.Replace("\r\n", "\r\n                          ");
            Console.WriteLine(string.Format("{0,-15} {1,-5} - {2}", logLevel, eventId, formatted));
        }
    }

然后,目的是什么,谁(为什么)调用IsEnabled.

Then what is the purpose and who(why) calls IsEnabled.

推荐答案

除非Microsoft对其进行了更改,否则,您应该自己调用 IsEnabled .

Unless Microsoft changed it, yes you are supposed to call IsEnabled yourself.

原因是,如果API将调用IsEnabled,然后用户的代码调用IsEnabled,则这将使每个日志操作的调用次数增加一倍,并且会大大提高性能,最终超出其帮助范围.

The reasoning is that if the API would call IsEnabled, and then the user's code calls IsEnabled, that would double the calls per log operation and would hit performance more than it helps eventually.

此外,在向日志接收器写入内容之前,日志记录框架将始终尊重过滤器和最小日志级别.这意味着,如果您始终调用例如 LogDebug ,并且 Information 是已配置的最低日志级别,则调试消息将不会出现在日志中.

Also, the logging framework would always respect filters and min log level before writing something to the log sinks. Meaning, if you always call LogDebug for example and Information is your configured minimum log level, the debug messages will not appear in the log.

但是!如果您不检查 logger.IsEnabled(LogLevel.Debug)并仅在必要时运行该代码,则调用 LogDebug 和过滤的代码将被执行.

But! the code to call LogDebug and filtering gets excecuted if you do not check for logger.IsEnabled(LogLevel.Debug) and run the code only if necessary.

有意义的希望

这篇关于ILogger(ASP.NET Core)日志甚至被称为IsEnabled返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆