How to use custom sys.excepthook in RootController in TurboGears 2.2.2

I want all exceptions from the log file to be logged in my TB application. So, I tried to use custom sys.excepthook, as usual. But every exception still occurs 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 call ValueError in the 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 I am doing wrong? Any idea?

+4
source share
1 answer

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

When an exception is thrown and fails, a call to the sys.excepthook interpreter [...] in the Python program occurs immediately before the program exits.

Now that WebError catches the exception and processes it (your application doesn't even get out of such exceptions), the exception does not reach the point at which sys.excepthook is sys.excepthook .


For a quick and dirty solution, you can try setting full_stack = False in your configuration to disable WebError middleware ( https://github.com/TurboGears/tg2/blob/tg2.2.2/tg/configuration/app_config.py#L1036 ) . of course, implies that you are processing failure response codes on your web server.

If you just want to log an exception, but still use the WebError debug / email function, you can simply set up your own middleware, wrap it around your application, register an exception and pass it.

+2
source

Source: https://habr.com/ru/post/1496997/


All Articles