python3 下记录中文日志要使用 encoding 参数,否则会有以下错误:
--- Logging error ---
Traceback (most recent call last):
File "/Users/evil/.pyenv/versions/3.6.2/lib/python3.6/logging/__init__.py", line 994, in emit
stream.write(msg)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 33-34: ordinal not in range(128)
Call stack:
File "/Users/evil/git/jianshu/crawl_jobs/crawl.py", line 70, in
LOGGER.info("测试")
Message: '测试'
Arguments: ()
修改相关配置
log_name = '2018-05-12.log'
logging.basicConfig(format='[%(asctime)s %(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG, filename=log_name)
LOGGER = logging.getLogger(__name__)
# 新增 fh,修改 basicConfig
fh = logging.FileHandler(encoding='utf-8', mode='a', filename=log_name)
logging.basicConfig(handlers=[fh], format='[%(asctime)s %(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
# 此时中文日志可正常输出
LOGGER.info("测试")
basicConfig 的作用是快速配置日志系统,当有 filename 参数时,自动创建一个 FileHandler 进行日志记录。目前版本的 basicConfig 无法传递 encoding 参数,因此直接传入一个 FileHandler,而 handlers 是要接收一个可迭代对象。