用装饰器实现把函数用try...except包起来:
import logging import traceback from functools import wraps logging.basicConfig(filename='error.log', level=logging.INFO, format='%(levelname)s::%(name)s::%(asctime)s::%(filename)s,line %(lineno)s, in %(funcName)s(),msg:%(message)s' ) #定义装饰器error_handler def error_handler(func): @wraps(func) #关键行 def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: msg=traceback.format_exc() logging.error(msg) return 'error' return wrapper #返回函数名 #用法示例:自动处理test()的异常 @error_handler def test(): a=1/0 return a if __name__=='__main__': test()