简体   繁体   English

基于变量值的Python日志记录级别?

[英]Python logging level based on variable value?

I need to change the logging level based on the value of a variable. 我需要根据变量的值更改日志记录级别。 For example: 例如:

if accel >= 10.0:
    log_func = logging.critical # Critical for splat event
elif accel >= 2.0:
    log_func = logging.warning  # Warning for high-G
elif accel >= 1.0:
    log_func = logging.info     # Info for normal
else:
    log_func = logging.debug    # Debug otherwise
log_func("Collision with %0.1fG impact.", accel)

I have instances of this all through my code. 我通过我的代码完成了这个实例。 Is there a better way? 有没有更好的办法?

Yes, use the Logger.log() method instead, and pass in a level constant: 是的,改为使用Logger.log()方法,并传入一个级别常量:

import sys

# Map accel values to log levels
levels = (
    (10.0, logging.CRITICAL),
    (2.0, logging.WARNING), 
    (1.0, logging.INFO),
    (-sys.maxsize, logging.DEBUG)
)

logging.log(next(lev[1] for lev in levels if lev[0] <= accel),
    "Collision with %0.1fG impact.", accel)

You could encapsulate the level selection into a utility function: 您可以将级别选择封装到实用程序函数中:

def level_for_accel(accel):
    # return next matching log level for the given accel value
    return next(lev[1] for lev in levels if lev[0] <= accel)

logging.log(level_for_accel(accel), "Collision with %0.1fG impact.", accel)

Log levels are really integers, and the CRITICAL , WARNING , etc. values are merely constants. 日志级别实际上是整数,而CRITICALWARNING等值仅仅是常量。 There are any number of ways you can turn one value (eg accel ) into a matching log level with a few simple rules, in a more readable manner than a large number of if / else branches. 有许多方法可以将一个值(例如accel )转换为具有一些简单规则的匹配日志级别,其方式比大量if / else分支更易读。

You could create a function which takes the variable accel and returns the appropriate logging function. 您可以创建一个获取变量accel并返回相应日志记录功能的函数。 and then call that. 然后打电话给那个。 It would probably be cleaner and more maintainable code. 它可能是更干净,更易于维护的代码。 Not to mention DRY. 更不用说干了。

def logger(accel):
    if accel >= 10.0:
        return logging.critical # Critical for splat event
    if accel >= 2.0:
        return logging.warning  # Warning for high-G
    if accel >= 1.0:
       return logging.info     # Info for normal
   else:
       return logging.debug    # Debug otherwise

Then you could use it as 然后你可以用它作为

logger(12)("hello world")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM