/blogmaker/util/trap_errors.py

http://blogmaker.googlecode.com/ · Python · 35 lines · 19 code · 7 blank · 9 comment · 5 complexity · f2df33e1637b78cf06877af80d6fb6ef MD5 · raw file

  1. ''' Helpers that trap and log errors.
  2. Copyright (c) 2006-2007, PreFab Software Inc. '''
  3. from __future__ import with_statement
  4. from contextlib import contextmanager
  5. from functools import wraps
  6. import logging
  7. @contextmanager
  8. def error_trapping(ident=None):
  9. ''' A context manager that traps and logs exception in its block.
  10. Usage:
  11. with error_trapping():
  12. might_raise_exception()
  13. this_will_always_be_called()
  14. '''
  15. try:
  16. yield None
  17. except Exception:
  18. if ident:
  19. logging.error('Error in %s' % ident, exc_info=True)
  20. else:
  21. logging.error('Error', exc_info=True)
  22. def trap_errors(f):
  23. ''' A decorator to trap and log exceptions '''
  24. @wraps(f)
  25. def wrapper(*args, **kwds):
  26. with error_trapping(f.__name__):
  27. return f(*args, **kwds)
  28. return wrapper