• Python部分异常日志缺失


    0、问题

    python使用logging时,部分异常日志缺失

    1、正常启动

    每个进程都有三个流(stdin[0],stdout[1],stderr[2])
    标准print输出到stdout,未捕获的异常等输出到stderr,或者通过下列方式

    print >> sys.stderr, "spam"
     
    sys.stderr.write("spam\n")
     
    os.write(2, b"spam\n")
    
    print("spam", file=sys.stderr)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    如果使用pycharm,则默认控制台黑色为stdout,红色为stderr。

    1.1、无管道符

    python test.py:
    默认控制台输入:stdin
    默认控制台输出:stdout,stderr

    1.2、定向stdout

    python test.py > 1.txt
    将stdout定向到1.txt,即将其内容输出到1.txt中,
    此时stderr内容还是输出到控制台中(未捕获的异常等)

    1.3、定向stdout和stderr

    python test.py > 1.txt 2>2.txt
    将stdout定向到1.txt,即将其内容输出到1.txt中,
    将stderr定向到2.txt,即将其内容输出到2.txt中

    1.4、常见启动命令

    python test.py > /dev/null 2>&1
    将stdout定向到/dev/null中,即不保存其内容,同时2>&1(加&为了区分2>1(表示输出到文件1中)),将stderr定向到stdout。所以stdout和stderr信息都没有了,只有使用logging的FileHandler保存信息。logging的FileHandler只有使用其logger时才输出。

    本质上:当使用logging后日志打印,一般会有两种Handler,一种StreamHandler(配置sys.stdout,不然使用logger的info等控制台无输出),一种FileHandler。
    当我们调用其info,warning,error时,如果logger配置了两种handler后,才会控制台打印并同时输出到文件中,而此时出现的为捕获异常还是stderr中。
    但stderr默认输出到控制台中,所以当未定向stderr时,控制台可以看到异常信息,但日志文件中没有。

    1.5、问题缘由

    未try catch的异常会默认输出到stderr中,默认使用logging的logger打印日志时,logger没有保存相关stderr的信息,所以导致日志缺失。

    2、解决方案

    2.1、回调函数

    未捕获的异常默认输出为stderr,所以需要修改其输出。
    python中有异常回调钩子:
    sys.excepthook,threading.excepthook.
    所以将其从默认的stderr,通过调用log日志打印保存异常信息。

    # 未被捕获的异常处理
    def handle_exception(exc_type, exc_value, exc_traceback):
        if issubclass(exc_type, KeyboardInterrupt):
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        logger.error("Uncaught exception:", exc_info=exc_value)
    
    def thread_handle_exception(args):
        logger.error("Thread uncaught exception:", exc_info=(args.exc_type, args.exc_value, args.exc_traceback))
    
    # 异常函数钩子
    sys.excepthook = handle_exception
    # 线程内异常函数钩子
    threading.excepthook = thread_handle_exception
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • 相关阅读:
    c#使用ExifLib库提取图像的相机型号、光圈、快门、iso、曝光时间、焦距信息等EXIF信息
    线上展厅功能要点
    Redis的集群模式搭建
    【编程题】【Scratch四级】2021.03 十字回文诗
    DateTime 相关的操作汇总【C# 基础】
    DDD与微服务的千丝万缕
    手动dump失败问题
    【论文阅读】Dense Passage Retrieval for Open-Domain Question Answering
    通过语言大模型来学习LLM和LMM(四)
    springboot毕设项目城市地铁线路与站点查询系统528h5(java+VUE+Mybatis+Maven+Mysql)
  • 原文地址:https://blog.csdn.net/qq_43621091/article/details/125607908