Can I make Python output exceptions in one line / via logging?

前端 未结 3 1319
南方客
南方客 2021-01-17 16:18

I am using AWS and use AWS cloudwatch to view logs. While things should not break on AWS, they could. I just had such a case. Then I searched for Traceback and

3条回答
  •  天命终不由人
    2021-01-17 16:46

    You can use sys.excepthook. It is invoked whenever an exception occurs in your script.

    import logging
    import sys
    import traceback
    
    def exception_logging(exctype, value, tb):
        """
        Log exception by using the root logger.
    
        Parameters
        ----------
        exctype : type
        value : NameError
        tb : traceback
        """
        write_val = {'exception_type': str(exctype),
                     'message': str(traceback.format_tb(tb, 10))}
        logging.exception(str(write_val))
    

    Then in your script you have to override the value of sys.excepthook.

    sys.excepthook = exception_logging
    

    Now whenever an exception occurs it will be logged with your logger handler.

    Note: Don't forget to setup logger before running this

提交回复
热议问题