logging 日志模块写入中文编码错误解决方法
在logging.FileHandler(path) 中添加指定编码方式 encoding=’utf-8’ 即可,logging.FileHandler(path, encoding=’utf-8’) 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 18/8/16 10:40 # @Author : Medivh
import functools import logging import logging.handlers import os
LOG_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logs', 'logger.log') handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=10, encoding='utf-8') fmt = '[%(levelname)s]: %(asctime)s - %(filename)s - %(funcName)s - %(threadName)s - %(message)s'
formatter = logging.Formatter(fmt) handler.setFormatter(formatter)
logger = logging.getLogger('logger') logger.addHandler(handler) logger.setLevel(logging.INFO)
def log(func): @functools.wraps(func) def wrapper(*args, **kw): logging.info('call %s():' % func.__name__) return func(*args, **kw)
return wrapper
|