动态调整logging日志级别
动态调整logging日志级别
import logging
import os
def set_log(log_path):
log_format = logging.Formatter(fmt='[%(asctime)s][%(module)s][%(levelname)s]: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
log_level = logging.INFO
log_output = logging.StreamHandler()
log_output.setLevel(log_level)
log_output.setFormatter(log_format)
# addHandler是将handler append到一个列表中,因此是有序的
logger.addHandler(log_output)
log_level = logging.INFO
if not os.path.exists(os.path.dirname(log_path)):
os.makedirs(os.path.dirname(log_path))
log_file_path = log_path
log_dir = os.path.dirname(log_file_path)
if not os.path.isdir(log_dir):
os.makedirs(log_dir)
file_log = logging.FileHandler(log_file_path)
file_log.setLevel(log_level)
file_log.setFormatter(log_format)
logger.addHandler(file_log)
return logger
def main():
set_log('/data/users/fhu/PycharmProjects/Buildflow/test_demo/test_log.log')
logging.info('1111111111111111111111')
# print(len(logging.getLogger().handlers))
# logging.getLogger().handlers可以获取已配置好的所有handler
all_handlers = logging.getLogger().handlers
for index, handler in enumerate(all_handlers):
print(handler)
print(type(handler))
if isinstance(handler, logging.StreamHandler):
print('stream')
else:
print('file')
console_handler = all_handlers[0]
old_level = console_handler.level
console_handler.setLevel(logging.WARNING)
logging.info('222222222222222222')
console_handler.setLevel(old_level)
logging.info('333333333333333333')
if __name__ == '__main__':
main()
结果示例: