def my_function():
logging.debug('Some debug data')
logging.error('Error log here')
logging.debug('More debug data')
有这样一个函数,它的默认日志级别是WARNING,所以只会把大于等于WARNING 级别的日志打印出来
要想临时改变日志级别,可以定义情景管理器(context manager)。用@contextmanager来修饰下面这个辅助函数,就能定义出这样一个管理器
@contextmanager
def debug_logging(level):
logger = logging.getLogger()
old_level = logger.getEffectiveLevel()
logger.setLevel(level)
try:
yield
finally:
logger.setLevel(old_level)
if __name__ == '__main__':
with debug_logging(logging.DEBUG):
print('* Inside:')
my_function()
print('* after:')
my_function()
'''
* Inside:
DEBUG:root:Some debug data
ERROR:root:Error log here
DEBUG:root:More debug data
* after:
ERROR:root:Error log here
'''
标签:__,情景,管理器,Python,debug,logging,logger,data
From: https://www.cnblogs.com/czzz/p/17019650.html