为什么无论级别如何,python 中的日志记录语句都会被评估?
例如,在这段代码中,我希望只有在使用“-d”调用脚本时才会打印“我被执行”语句,但它总是会打印出来!这意味着日志记录语句可能会对以更高日志记录级别运行的代码产生意想不到的影响。
#!/usr/bin/env python3
#import time
import argparse
import logging
logging.basicConfig(format='==> %(module)s, %(funcName)s %(message)s', level=logging.ERROR)
def logme():
#time.sleep(10)
print('I was executed ☠')
return 'loggging all the things...'
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--debug", "-d",
action='store_true',
help="Debug mode (very verbose)",
)
args = parser.parse_args()
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
print('hello')
logging.debug('{}'.format(logme()))
print('bye')
这是日志模块中的错误吗?
请您参考如下方法:
它归结为如何评估语句。在
logging.debug('{}'.format(logme()))
首先评估参数,然后调用 logger.debug。因此,我们评估 '{}'.format(logme()),然后将结果传递给 logging.debug。这是有效的
x = '{}'.format(logme())
logging.debug(x)
让我们测试一下:
def run_later(x):
print("function call")
def effect():
print("parameter evaluation")
run_later(effect())
>>> parameter evaluation
>>> function call
