生成的文件有问号标识无法打开时,多数情况均为文件编码格式问题,pycharm默认为GBK格式,需要转为UTF-8
找到输出日志的模块,logging.FileHandler方法添加encoding编码格式即可
实例:file_log = logging.FileHandler(self.logfile_path,encoding='UTF-8')
源代码如下:
import os
import logging
current_path = os.path.dirname(__file__)
log_path = os.path.join(current_path,'../logs/test.log')
class LogUtils:
def __init__(self,logfile_path=log_path):
self.logfile_path = logfile_path
self.logger = logging.getLogger('Logger')#获取logger对象
self.logger.setLevel(level=logging.INFO)#设置日志级别
file_log = logging.FileHandler(self.logfile_path,encoding='UTF-8')#将日志记录发送到对应路径
formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')#指定日志输出的具体格式
file_log.setFormatter(formatter)#将formatter绑定到file_log上
self.logger.addHandler(file_log)#将handler添加到对应对象中
def info(self,message):
self.logger.info(message)
def error(self,message):
self.logger.error(message)
logger = LogUtils()
if __name__ == '__main__':
log_utils = LogUtils()
log_utils.info('wanzi')