【Python】裝飾器實現日志記錄


好的日志對一個軟件的重要性是顯而易見的。如果函數的入口都要寫一行代碼來記錄日志,這種方式實在是太低效了,但一直沒有找到更好的方法。后來用python寫一些軟件,了解到python的裝飾器功能時,突然人品爆發,結合裝飾器來記錄日志那是絕對的簡單有效!

 

下面簡單演示一下用裝飾器來協助記錄Log,示例代碼如下:

 

  1. #!/usr/bin/env python  
  2. def trace_func(func):  
  3.     ''''' 
  4.     A decorate function to track all function invoke information with DEBUG level 
  5.     Usage: 
  6.     @trace_func 
  7.     def any_function(any parametet) 
  8.     '''  
  9.     def tmp(*args, **kargs):  
  10.         print 'Start %s(%s, %s)...' % (func.__name__, args, kargs)  
  11.         return func(*args, **kargs)  
  12.     return tmp  
  13. @trace_func  
  14. def log_test_with_empty_parameter():  
  15.     pass  
  16. @trace_func  
  17. def log_test_with_many_parameter(a_int, b_string, c_list, d_dict):  
  18.     pass  
  19. @trace_func  
  20. def log_test_with_key_parameter(a = 'www', b = 1, c = [1,2]):  
  21.     pass  
  22. if __name__ == '__main__':  
  23.     log_test_with_empty_parameter()  
  24.       
  25.     log_test_with_many_parameter(1, 'wwww', [1,2,'c'], {1: 'a', 2 : 'ww'})  
  26.     log_test_with_key_parameter(1, 'wwww', c = [3, 4])  

 

 

 

運行結果如下:

 

 

  1. [root@localhost python2]# ./a.py   
  2. Start log_test_with_empty_parameter((), {})...  
  3. Start log_test_with_many_parameter((1, 'wwww', [1, 2, 'c'], {1: 'a', 2: 'ww'}), {})...  
  4. Start log_test_with_key_parameter((1, 'wwww'), {'c': [3, 4]})... 

參考資料:

Python 日志方法(裝飾器):http://www.thinksaas.cn/group/topic/92386/

利用python的裝飾器函數來記錄日志:http://blog.csdn.net/guosha/article/details/6457171

Python精選文章: 裝飾器與AOP:http://www.django-china.cn/topic/148/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM