Mayil-AI / loguru

MIT License
0 stars 0 forks source link

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

Open vikramsubramanian opened 3 months ago

vikramsubramanian commented 3 months ago

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](

)

mayil-ai[bot] commented 3 months ago

To log the full exception traceback when using sys.excepthook for unhandled exceptions, you should modify the handle_exception function to directly use the exc_traceback parameter instead of calling sys.exc_info(). Here's the corrected code snippet:

import sys
from loguru import logger

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

    logger.opt(exception=(exc_type, exc_value, exc_traceback)).exception("Uncaught Exception")

sys.excepthook = handle_exception

In the handle_exception function, the logger.opt(exception=(exc_type, exc_value, exc_traceback)).exception("Uncaught Exception") line is used to log the exception with the traceback. The exception parameter of logger.opt is set to a tuple containing the exception type, value, and traceback, which is the correct way to log the full traceback of unhandled exceptions.