Skip to content

[Question] How do I log full exception traceback when using sys.excepthook for unhandled excpetions (hashtag1067) #9

Description

@vikramsubramanian

I cannot work out how to log uncaught exceptions with the same output as caught exceptions. The below shows the code I used to compare the differences in the exception log. I would appreciate help on working out the correct way to achieve this.

import sys, traceback
from loguru import logger

def divide(a, b):
    return a/b

def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    exception = sys.exc_info()
    logger.opt(exception=exception).exception("Uncaught Exception")

sys.excepthook = handle_exception

print("*************************************************************")
print("***********         Caught Exception            *************")
print("*************************************************************")

try:
    divide(2,0)
except:
    logger.exception("Caught Exception")

print("*************************************************************")
print("**********         Uncaught Exception            ************")
print("*************************************************************")

divide(2,0)

Output
![image](

)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions