python调试利器:最直观简洁的错误日志

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-08-30 17:12:27
# @Author  : Sheldon (thisisscret@qq.com)
# @Blog    : 谢耳朵的派森笔记
# @Link    : https://www.cnblogs.com/shld/
# @Version : 0.0.1

 

import logging
from better_exceptions import format_exception
import better_exceptions


def getLogger(name: str = None, mode="ch", level="DEBUG", filename=None):
    # 返回一个looger,当调用exception方法时,将显示报错参数的详情
    # fh为写入文件模式,filename是日志模式的文件名或文件路径加文件名
    # ch为控制台模式,即打印在控制台,不写入文件
    logger = logging.getLogger(name)
    logger.propagate = False
    logger.handlers.clear()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    formatter.formatException = lambda exc_info: format_exception(*exc_info)
    if mode == "fh":
        better_exceptions.SUPPORTS_COLOR = False
        handler = logging.FileHandler(filename or f"{name or 'temp'}.log")
    elif mode == "ch":
        handler = logging.StreamHandler()
    else:
        raise ValueError("Mode模式错误,应为'ch'[控制台输出模式] 或 'fh'[日志输出模式]")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(level)
    return logger


if __name__ == "__main__":

    def makeerror():
        console = getLogger('makeerror')
        try:
            a = 1
            b = 0
            c = a / b
            return c
        except Exception as e:
            console.exception(e)


    makeerror()

    console1 = getLogger("又红又专的谢耳朵")
    console1.info('我们的祖国是花园...')

输出结果:

 

 

posted @ 2018-09-10 00:20  谢耳朵的派森笔记  阅读(502)  评论(0编辑  收藏  举报