Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 589|回复: 0

python中如何用sys.excepthook来对全局异常进行捕获、显示及输出到error日志中

[复制链接]
  • TA的每日心情
    奋斗
    2024-4-6 11:05
  • 签到天数: 748 天

    [LV.9]以坛为家II

    2034

    主题

    2092

    帖子

    70万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    705612
    发表于 2021-5-23 07:19:49 | 显示全部楼层 |阅读模式

    使用sys.excepthook函数进行全局异常的获取。

    1. 使用MessageDialog实现异常显示;

    2. 使用logger把捕获的异常信息输出到日志中;

    步骤:定义异常处理函数, 并使用该函来替换掉系统的内置处理函数;

    对于threading.py的异常捕获,需要对该文件进行一些改变:

    如下:

    try:
                    self.run()
                except SystemExit:
                    if __debug__:
                        self._note("%s.__bootstrap(): raised SystemExit", self)
                except:
                    if __debug__:
                        self._note("%s.__bootstrap(): unhandled exception", self)
                    # If sys.stderr is no more (most likely from interpreter
                    # shutdown) use self.__stderr.  Otherwise still use sys (as in
                    # _sys) in case sys.stderr was redefined since the creation of
                    # self.
                    if _sys:
                        if id(_sys.excepthook) != id(_sys.__excepthook__):  
                            exc_type, exc_value, exc_tb = self.__exc_info()  
                            _sys.excepthook(exc_type, exc_value, exc_tb)  
                         
                        _sys.stderr.write("Exception in thread %s:\n%s\n" %
                                              (self.name, _format_exc()))

     

    #-*- coding: UTF-8 -*-
    #-------------------------------------------------------------------------------
    # Name:        模块except hook handler 
    # Purpose:     全局捕获异常
    #
    # Author:      ankier
    #
    # Created:     17-08-2013
    # Copyright:   (c) ankier 2013
    # Licence:     <your licence>
    #-------------------------------------------------------------------------------
    
    import logging
    import sys
    import traceback 
    import datetime
    import wx
    
    ## @detail 创建记录异常的信息
    class ExceptHookHandler(object):
        ## @detail 构造函数
        #  @param logFile: log的输入地址
        #  @param mainFrame: 是否需要在主窗口中弹出提醒
        def __init__(self, logFile, mainFrame = None):
            self.__LogFile = logFile
            self.__MainFrame = mainFrame
            
            self.__Logger = self.__BuildLogger()
            #重定向异常捕获
            sys.excepthook = self.__HandleException
        
        ## @detail 创建logger类
        def __BuildLogger(self):
            logger = logging.getLogger()
            logger.setLevel(logging.DEBUG)
            logger.addHandler(logging.FileHandler(self.__LogFile))
            return logger
        
        ## @detail 捕获及输出异常类
        #  @param excType: 异常类型
        #  @param excValue: 异常对象
        #  @param tb: 异常的trace back
        def __HandleException(self, excType, excValue, tb):
            # first logger 
            try:
                currentTime = datetime.datetime.now()
                self.__Logger.info('Timestamp: %s'%(currentTime.strftime("%Y-%m-%d %H:%M:%S")))
                self.__Logger.error("Uncaught exception:", exc_info=(excType, excValue, tb))
                self.__Logger.info('\n')
            except:
                pass
            
            # then call the default handler
            sys.__excepthook__(excType, excValue, tb)     
            
            err_msg = ''.join(traceback.format_exception(excType, excValue, tb))
            err_msg += '\n Your App happen an exception, please contact administration.'
            # Here collecting traceback and some log files to be sent for debugging.
            # But also possible to handle the error and continue working.
            dlg = wx.MessageDialog(None, err_msg, 'Administration', wx.OK | wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy() 
            
    
            

    输出效果:

    log输出文件:

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-18 15:46 , Processed in 0.060588 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表