1. 程式人生 > >python 寫入日誌的問題 UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position 0: illegal multibyte sequence UnicodeEnco

python 寫入日誌的問題 UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position 0: illegal multibyte sequence UnicodeEnco

最近,使用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