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

前端 未结 3 1213
南方客
南方客 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

    In case somebody wants the exception logged in its default format, but in one line (for any reason), based on the accepted answer:

    def exception_logging(exctype, value, tb):
        """
        Log exception in one line by using the root logger.
    
        Parameters
        ----------
        exctype : exception type
        value : seems to be the Exception object (with its message)
        tb : traceback
        """
        logging.error(''.join(traceback.format_exception(exctype, value, tb)))
    

    Please also note, that it uses logging.error() instead of logging.exception() which also printed some extra "NoneType: None" line.
    Also note that it only seems to work with uncaught exceptions.
    For logging caught exceptions, visit How do I can format exception stacktraces in Python logging? and see also my answer.

提交回复
热议问题