python3 下記錄中文日志要使用 encoding 參數(shù),否則會(huì)有以下錯(cuò)誤:
--- 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 <module>
LOGGER.info("測試")
Message: '測試'
Arguments: ()
修改相關(guān)配置
log_name = '2018-05-12.log'
logging.basicConfig(format='[%(asctime)s %(levelname)s]<%(process)d> %(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]<%(process)d> %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
# 此時(shí)中文日志可正常輸出
LOGGER.info("測試")
basicConfig 的作用是快速配置日志系統(tǒng)畅买,當(dāng)有 filename 參數(shù)時(shí),自動(dòng)創(chuàng)建一個(gè) FileHandler 進(jìn)行日志記錄匙奴。目前版本的 basicConfig 無法傳遞 encoding 參數(shù)魄健,因此直接傳入一個(gè) FileHandler,而 handlers 是要接收一個(gè)可迭代對(duì)象旋奢。