Question

I want in my TB app to log all exceptions to a log file. So, I tried to use custom sys.excepthook as usual. But every exception is still raised and nothing is logged. Here is my code:

class RootController(BaseController):
    secc = SecureController()
    error = ErrorController()

    def __init__(self):
        self.installExceptHook()
        super(RootController, self).__init__()

    def installExceptHook(self):
        def exceptHook(type, value, tb):
            logger = logging.getLogger('app')
            logger.critical(''.join(traceback.format_exception(type, value, tb)))
        sys.excepthook = exceptHook

When I raise ValueError in index method:

@expose('app.templates.index')
def index(self, **kwargs):
    raise ValueError
    return dict(page = 'index')

I still get the WebError Traceback page in my browser and nothing is logged.

Do you know what am I doing wrong? Any idea?

Was it helpful?

Solution

From the docs (http://docs.python.org/2/library/sys.html#sys.excepthook):

When an exception is raised and uncaught, the interpreter calls sys.excepthook [...] in a Python program this happens just before the program exits.

Now since WebError catches the exception and handles it (your application doesn't even exit from such exceptions), the exception doesn't reach the point where sys.excepthook gets called.


For a quick and dirty solution, you could try setting full_stack = False in your configuration to disable the WebError middleware (https://github.com/TurboGears/tg2/blob/tg2.2.2/tg/configuration/app_config.py#L1036) this would of course imply that you handle failure response codes in your webserver.

If you just want to log the exception but still use the WebError debugging/eMail functionality, you could just set up a custom middleware, wrap it around your application, log the exception and pass it on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top