本文實(shí)例講述了Python使用logging結(jié)合decorator模式實(shí)現(xiàn)優(yōu)化日志輸出的方法。分享給大家供大家參考,具體如下:
python內(nèi)置的loging模塊非常簡(jiǎn)便易用, 很適合程序運(yùn)行日志的輸出。
而結(jié)合python的裝飾器模式,則可實(shí)現(xiàn)簡(jiǎn)明實(shí)用的代碼。測(cè)試代碼如下所示:
#! /usr/bin/env python2.7# -*- encoding: utf-8 -*-import logginglogging.basicConfig(format='[%(asctime)s] %(message)s', level=logging.INFO)def time_recorder(func): """裝飾器, 用在func方法執(zhí)行前后, 增加運(yùn)行信息""" 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() 運(yùn)行并得到輸出:
[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



















