• 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('我们的祖国是花园...')

    输出结果:

     

  • 相关阅读:
    Android学习笔记安卓基础知识
    V8编程1
    dfdf
    NodeJS沙箱
    CGI编程cgihtml库简析
    dsfdsf
    Android学习笔记获取屏幕大小
    Android学习笔记AndroidManifest.xml配置文件详解
    HTTP状态码解析
    简易c++版本日志库
  • 原文地址:https://www.cnblogs.com/shld/p/9616183.html
Copyright © 2020-2023  润新知