本文实例讲述了python使用logging结合decorator模式实现优化日志输出的方法。分享给大家供大家参考,具体如下:
python内置的loging模块非常简便易用, 很适合程序运行日志的输出。
而结合python的装饰器模式,则可实现简明实用的代码。测试代码如下所示:
#! /usr/bin/env python2.7# -*- encoding: utf-8 -*-import logginglogging.basicConfig(format='[%(asctime)s] %(message)s', level=logging.INFO)def time_recorder(func): """装饰器, 用在func方法执行前后, 增加运行信息""" def wrapper(): logging.info("Begin to execute function: %s" % func.__name__) func() logging.info("Finish executing function: %s" % func.__name__) return wrapper@time_recorderdef first_func(): print "I'm first_function. I'm doing something..."@time_recorderdef second_func(): print "I'm second_function. I'm doing something..."if __name__ == "__main__": first_func() second_func()
登录后复制
运行并得到输出:
[2014-04-01 18:02:13,724] Begin to execute function: first_funcI'm first_function. I'm doing something...[2014-04-01 18:02:13,725] Finish executing function: first_func[2014-04-01 18:02:13,725] Begin to execute function: second_funcI'm second_function. I'm doing something...[2014-04-01 18:02:13,725] Finish executing function: second_func
登录后复制
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
立即学习“Python免费学习笔记(深入)”;
希望本文所述对大家Python程序设计有所帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2536438.html