【发布时间】:2018-12-14 15:29:39
【问题描述】:
为什么不管级别如何,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')
这是日志模块中的错误吗?
【问题讨论】:
-
你调用了
logme()之前将它传递给str.format()调用,更不用说在str.format()的结果被传递给logging.debug()之前。这只是表达式的标准执行顺序。
标签: python python-3.x logging