本文实例讲述了Python使用logging结合decorator模式实现优化日志输出的方法。分享给大家供大家参考,具体如下:
python内置的loging模块非常简便易用, 很适合程序运行日志的输出。
而结合python的装饰器模式,则可实现简明实用的代码。测试代码如下所示:
#! /usr/bin/env python2.7 # -*- encoding: utf-8 -*- import logging logging.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_recorder def first_func(): print "I'm first_function. I'm doing something..." @time_recorder def 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_func I'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_func I'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程序设计有所帮助。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月25日
2024年09月25日
- 纯音入心系列纯音乐《天籁古筝》1CD[MP3][331MB]
- 男女对唱典藏天碟《发烧对唱·那个季节里的歌DSD》10CD[WAV]
- 群星2010-歌林精选辑[歌林][WAV+CUE]
- TrioZimbalist-PianoTriosofWeinberg,Auerbach,Dvorak(2024)[24-44,1]wav
- 群星.1992-滚石第一流台湾歌·12王牌大车拼【滚石】【WAV+CUE】
- 林子祥.1984-创作歌集【华纳】【WAV+CUE】
- 周汤豪.2010-周汤豪【华纳】【FLAC分轨】
- Mozart-TheStringQuintets-AmadeusQuartet,CecilAronowitz(2017)[24-44,1][WAV+CUE]
- JamesWilliamsDennisIrwin-Focus(2024,Red)[24-48]FLAC
- 藤泽麻衣《空みあげて》[WAV]
- 纯音入心系列纯音乐《中国古筝经典名曲》1CD[MP3][1.3GB]
- 纯音入心系列纯音乐《古筝新奏:岁月静好与筝语,细水流年与筝同》1CD[MP3][846.9MB]
- 670《脆弱敏感小女生》[320K/MP3][27.53MB]
- 曾琳.2011-好好爱我【南方】【WAV+CUE】
- 范晓萱.1995-RAIN【福茂】【WAV+CUE】