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

 def get_logger(log_file):
"""
进行日志操作,有专门的日志模块:logging
:param log_file:
:return:
"""
logger = logging.getLogger(log_file)
# 设置日志等级
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(log_file, encoding='utf8')
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fh)
return logger

  

上一篇:UnicodeEncodeError: 'utf-8' codec can't encode character '\udce4' in position 1: surrogates not allowed根本解决方法


下一篇:使用layer显示弹出框笔记