Python使用logging结合decorator模式实现优化日志输出的方法
本文实例讲述了Python使用logging结合decorator模式实现优化日志输出的方法。分享给大家供大家参考,具体如下:
python内置的loging模块非常简便易用,很适合程序运行日志的输出。
而结合python的装饰器模式,则可实现简明实用的代码。测试代码如下所示:
#!/usr/bin/envpython2.7 #-*-encoding:utf-8-*- importlogging logging.basicConfig(format='[%(asctime)s]%(message)s',level=logging.INFO) deftime_recorder(func): """装饰器,用在func方法执行前后,增加运行信息""" defwrapper(): logging.info("Begintoexecutefunction:%s"%func.__name__) func() logging.info("Finishexecutingfunction:%s"%func.__name__) returnwrapper @time_recorder deffirst_func(): print"I'mfirst_function.I'mdoingsomething..." @time_recorder defsecond_func(): print"I'msecond_function.I'mdoingsomething..." if__name__=="__main__": first_func() second_func()
运行并得到输出:
[2014-04-0118:02:13,724]Begintoexecutefunction:first_func I'mfirst_function.I'mdoingsomething... [2014-04-0118:02:13,725]Finishexecutingfunction:first_func [2014-04-0118:02:13,725]Begintoexecutefunction:second_func I'msecond_function.I'mdoingsomething... [2014-04-0118:02:13,725]Finishexecutingfunction:second_func
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。