您可能希望按照 unutbu 的建议进行操作,因为它更灵活,最终也同样简单。但是,如果您对 logging 的额外细节感到不知所措,请按照您的要求执行以下操作:
def exception_catch(log_path):
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
with open(log_path, 'a') as log:
log.write('{} {} {} {} {}\n'.format(datetime.datetime.now(),
type(e), e, args, kwargs))
# This will return None on error, of course
return wrapper
return deco
当然,您可以将任何您想要的内容放入format,包括来自上述任何作用域的任何局部变量。您要求的唯一棘手的一点是“代码中的异常行”。 2.x 与 3.x 的详细信息略有不同(请参阅traceback 模块了解您需要了解的大部分内容),但这里有一个 3.x 示例,可以准确地为您提供所需的内容:
except Exception as e:
filename, line, func, text = traceback.extract_stack(limit=1)[0]
with open(log_path, 'a') as log:
log.write('time: {} type: {} line: {} args: {}\n'.format(
datetime.datetime.now(),
type(e),
line,
args))