我一夜之间运行了一个Python脚本,发现日志文件只是我指定的消息格式的重复行,而不是实际的消息。在
main
模块中,我创建了如下记录器:
from datetime import datetime
import logging
import os
def main():
msg_format = '[%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d (%(funcName)s)] %(message)s'
logging.basicConfig(format=msg_format, level=logging.INFO)
logger = logging.getLogger()
logger.setLevel(level=logging.INFO)
timestamp = datetime.now().strftime(format='%Y%m%d-%H%M')
log_filename = '_'.join(['log', run_type, timestamp]) + '.txt'
save_pathname = '_'.join([run_type, datetime.now().strftime(format='%Y%m%d')])
save_path = os.path.join(save_path, save_pathname)
if not os.path.exists(save_path):
os.mkdir(path=save_path)
log_file = os.path.join(save_path, log_filename)
file_handler = logging.FileHandler(filename=log_file)
file_handler.setLevel(level=logging.INFO)
file_handler.setFormatter(fmt=msg_format)
logger.addHandler(hdlr=file_handler)
.
.
.
logger.info(msg='something')
整个模块中的语句。当我打开日志文件时,我看到的只是:
[%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d (%(funcName)s)] %(message)s
[%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d (%(funcName)s)] %(message)s
[%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d (%(funcName)s)] %(message)s
[%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d (%(funcName)s)] %(message)s
.
.
.
日志初始化的哪个部分出错了?我应该显式地设置吗
filemode='w'
在
logging.basicConfig
? 谢谢。