好的日志对一个软件的重要性是显而易见的。如果函数的入口都要写一行代码来记录日志,这种方式实在是太低效了,但一直没有找到更好的方法。后来用python写一些软件,了解到python的装饰器功能时,突然人品爆发,结合装饰器来记录日志那是绝对的简单有效!
下面简单演示一下用装饰器来协助记录Log,示例代码如下:
[python] view plain copy print?
- #!/usr/bin/env python
- def trace_func(func):
- ‘‘‘‘‘
- A decorate function to track all function invoke information with DEBUG level
- Usage:
- @trace_func
- def any_function(any parametet)
- ‘‘‘
- def tmp(*args, **kargs):
- print ‘Start %s(%s, %s)...‘ % (func.__name__, args, kargs)
- return func(*args, **kargs)
- return tmp
- @trace_func
- def log_test_with_empty_parameter():
- pass
- @trace_func
- def log_test_with_many_parameter(a_int, b_string, c_list, d_dict):
- pass
- @trace_func
- def log_test_with_key_parameter(a = ‘www‘, b = 1, c = [1,2]):
- pass
- if __name__ == ‘__main__‘:
- log_test_with_empty_parameter()
- log_test_with_many_parameter(1, ‘wwww‘, [1,2,‘c‘], {1: ‘a‘, 2 : ‘ww‘})
- log_test_with_key_parameter(1, ‘wwww‘, c = [3, 4])
#!/usr/bin/env python
def trace_func(func):
‘‘‘
A decorate function to track all function invoke information with DEBUG level
Usage:
@trace_func
def any_function(any parametet)
‘‘‘
def tmp(*args, **kargs):
print ‘Start %s(%s, %s)...‘ % (func.__name__, args, kargs)
return func(*args, **kargs)
return tmp
@trace_func
def log_test_with_empty_parameter():
pass
@trace_func
def log_test_with_many_parameter(a_int, b_string, c_list, d_dict):
pass
@trace_func
def log_test_with_key_parameter(a = ‘www‘, b = 1, c = [1,2]):
pass
if __name__ == ‘__main__‘:
log_test_with_empty_parameter()
log_test_with_many_parameter(1, ‘wwww‘, [1,2,‘c‘], {1: ‘a‘, 2 : ‘ww‘})
log_test_with_key_parameter(1, ‘wwww‘, c = [3, 4])
运行结果如下:
[python] view plain copy print?
- [[email protected] python2]# ./a.py
- Start log_test_with_empty_parameter((), {})...
- Start log_test_with_many_parameter((1, ‘wwww‘, [1, 2, ‘c‘], {1: ‘a‘, 2: ‘ww‘}), {})...
- Start log_test_with_key_parameter((1, ‘wwww‘), {‘c‘: [3, 4]})...
[root@localhost python2]# ./a.py
Start log_test_with_empty_parameter((), {})...
Start log_test_with_many_parameter((1, ‘wwww‘, [1, 2, ‘c‘], {1: ‘a‘, 2: ‘ww‘}), {})...
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/