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" 完美解决中文乱码的问题

你可能感兴趣的:(python logging模块写入中文,文件乱码的解决方法)