Python使用logging結合decorator模式實現最佳化日誌輸出的方法

來源:互聯網
上載者:User
本文執行個體講述了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程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.