为每一个计算过程创建一个单独的日志文件,并写入对应的结果,同时保留控制台输出的功能,控制台输出与日志文件记录可以分开单独控制。
import os
import shutil
import logging
def creat_logger(log_path,logging_name,suf_name):
if not os.path.exists(log_path):
os.makedirs(log_path)
log_full_path = log_path + logging_name + suf_name
logger = logging.getLogger(logging_name)
logger.setLevel(level=logging.DEBUG)
handler = logging.FileHandler(log_full_path, encoding='UTF-8',mode = 'w')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.addHandler(console)
return logger
if __name__ =='__main__':
if os.path.exist('./log/'):
shutil.rmtree('./log/')
for i in range(5):
for j in range(4):
log_trace = creat_logger('./log/i_loop'+str(i)+'/','j_loop'+str(j),'.txt')
log_trace.debug('DEBUG: iloop = %d , jloop = %d',i,j)
log_trace.info('INFO: iloop = %d , jloop = %d',i,j)
for handler in list(log_trace.handlers):
log_trace.removeHandler(handler)
控制台输出结果
日志文件输出