PageRenderTime 98ms CodeModel.GetById 94ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/blogmaker/util/trap_errors.py

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