python logging模块写入中文,文件乱码的解决方法

一下文件执行将产生乱码,切.log文件显示问好,打不开

import logging
def shop_logging(name):
    name = name+"登录成功!"
    logger = logging.getLogger()
    fh = logging.FileHandler("test.log")
    formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.setLevel(logging.DEBUG)
    logger.info(name)
shop_logging("auxc")

经发现,是没有定义文件格式,修复后

import logging
def shop_logging(name):
    name = name+"登录成功!"
    logger = logging.getLogger()
    fh = logging.FileHandler("test.log",encoding="utf-8",mode="a")
    formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.setLevel(logging.DEBUG)
    logger.info(name)
shop_logging("auxc")

加上 encoding="utf-8",mode="a" 完美解决中文乱码的问题

posted @ 2020-04-27 19:13  tooltime  阅读(1089)  评论(0编辑  收藏  举报