Why not just using Python's standard tools ? Like proper exception handling and using the logging
module ?
import logging
logger = logging.getLogger(__name__)
def func1(*params):
logger.debug("BEGIN func1(%s)", (params,))
session = Session()
try:
do_something_with(params)
except Exception as e:
logger.exception("FAILED func1(%s)", (params,))
logger.debug("ROLLINGBACK func1(%s)", (params,))
session.rollback()
logger.debug("ROLLEDBACK func1(%s)", (params,))
# if you don't handle exceptions let them propagate, thanks
raise
else:
logger.debug("SUCCEEDED func1(%s)", (params,))
# don't you need a session.commit() somewhere ???
finally:
logger.debug("CLOSING func1(%s)", (params,))
session.close()
logger.debug("CLOSED func1(%s)", (params,))
Now you just have to configure your logger and you'll probably find out what's going on much more quickly than you'll need to implement an half-baked ad-hoc solution.
Oh and if you have the very same pattern in more than a couple functions with only the params and "do_something_with(params) part differing, then wrap all the logging and transaction handling code in a decorator:
def manage(func):
def wrapper(*args, **kw):
session = Session()
try:
logger.debug("BEGIN %s(%s, %s)", (func, args,kw))
result = func(*args, **kw)
logger.debug("SUCCEEDED %s(%s, %s)", (func, args,kw))
# don't you need a session.commit() somewhere ???
return result
except Exception as e:
logger.exception("FAILED %s(%s, %s)", (func, args,kw))
logger.debug("ROLLINGBACK %s(%s, %s)", (func, args,kw))
session.rollback()
logger.debug("ROLLEDBACK %s(%s, %s)", (func, args,kw))
# if you don't handle exceptions let them propagate, thanks
raise
finally:
logger.debug("CLOSING %s(%s, %s)", (func, args,kw))
session.close()
logger.debug("CLOSED %s(%s, %s)", (func, args,kw))
return wrapper
@manage
def func1(*params):
do_something_with(params)