本文實例講述了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