python 写入日志的问题 UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position 0: illegal multibyte sequence
最近,使用python的logging模块,因为这个写入日志写完后就没有管它。在存储日志信息的时候,一直提示:
UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position 0: illegal multibyte sequence
还是以为是文件编码有问题,困扰了很久,其实是在写入日志时候提示的编码错误。
所以,需要对日志函数做一定的修改,编码改为utf-8
1 def get_logger(log_file): 2 """ 3 进行日志操作,有专门的日志模块:logging 4 :param log_file: 5 :return: 6 """ 7 logger = logging.getLogger(log_file) 8 # 设置日志等级 9 logger.setLevel(logging.DEBUG)
10 fh = logging.FileHandler(log_file, encoding='utf8')
11 fh.setLevel(logging.DEBUG) 12 ch = logging.StreamHandler() 13 ch.setLevel(logging.INFO) 14 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") 15 ch.setFormatter(formatter) 16 fh.setFormatter(formatter) 17 logger.addHandler(ch) 18 logger.addHandler(fh) 19 return logger
时刻记着自己要成为什么样的人!