python的logging写入日志时,中文总是乱码,即使py文件已经设置为utf8,也无济于事,
参考了上面的文章后,在初始化fileHandler时,增加了encoding=utf8即可,
tips:我并没有使用mode=a
# -*- coding:utf-8 -*-
import os,sys,logging
PY_GEN_PATH = os.getcwd()
cur_file = os.path.basename(sys.argv[0])
logger = logging.getLogger(cur_file)
def config_logger():
logger.setLevel(logging.DEBUG)
if not os.path.exists(PY_GEN_PATH):
logger.info("文件夹不存在,已自行创建")
os.makedirs(PY_GEN_PATH, 777)
handler = logging.FileHandler(os.path.join(PY_GEN_PATH, LOG_FILE),encoding='utf8')
handler.setLevel(logging.DEBUG)
fmter = logging.Formatter(LOG_FORMATTER)
handler.setFormatter(fmter)
logger.addHandler(handler)
# 控制台打印
console = logging.StreamHandler()
console.setLevel(level=logging.DEBUG) # 设置为INFO级别
console.setFormatter(fmter)
logger.addHandler(console)