zoukankan      html  css  js  c++  java
  • 【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程序员记录日志常用方法了。

    参考资料:

    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/

  • 相关阅读:
    Leetcode: Summary Ranges
    Leetcode: Kth Smallest Element in a BST
    Leetcode: Basic Calculator II
    Leetcode: Basic Calculator
    Leetcode: Count Complete Tree Nodes
    Leetcode: Implement Stack using Queues
    Leetcode: Maximal Square
    Leetcode: Contains Duplicate III
    Leetcode: Invert Binary Tree
    Leetcode: The Skyline Problem
  • 原文地址:https://www.cnblogs.com/junneyang/p/5332307.html
Copyright © 2011-2022 走看看