zoukankan      html  css  js  c++  java
  • @log的decorator完美实现(原创)

     1 # -*- coding: utf-8 -*-
     2 
     3 from functools import wraps
     4 from inspect import isfunction
     5 
     6 def beforecalled(*args, **kwargs):
     7     print('before called! {}'.format(len(args)))
     8 
     9     for arg in args:
    10         print(arg)        
    11 
    12 def aftercalled(*args, **kwargs):
    13     print('after called! {}'.format(len(args)))
    14     for k,v in kwargs.iteritems():
    15         print('{0}={1}'.format(k,v))
    16 
    17     jclist=['-' for _ in xrange(20)]
    18     print(''.join(jclist))
    19 
    20 def logdeco(*decoargs, **decokwargs):
    21     def decotator(func):
    22         @wraps(func)
    23         def wrapper(*funcargs, **funckwargs):
    24             beforecalled(*decoargs, **decokwargs)
    25             result = func(*funcargs, **funckwargs)
    26             aftercalled(*decoargs, **decokwargs)
    27             return result
    28         return wrapper
    29     return decotator
    30 
    31 def log(*decoargs, **decokwargs):
    32     if len(decoargs)==1 and len(decokwargs)==0:
    33         if isfunction(decoargs[0]) or hasattr(decoargs[0],'__call__'):
    34             return logdeco()(decoargs[0])
    35 
    36     def wrappered(func):
    37         return logdeco(*decoargs, **decokwargs)(func)
    38 
    39     return wrappered
    40 
    41 @log('lisa',50,email='lisa@xxx.com')
    42 def testmoreparas(x,y):
    43     print('x*y={}'.format(x*y))
    44 
    45 @log()
    46 def testemptypara(x,y):
    47     print('x*y={}'.format(x*y))
    48 
    49 @log
    50 def testjustlog(x,y):
    51     print('x*y={}'.format(x*y))    
    52 
    53 if __name__=='__main__':
    54     testmoreparas(5,6)
    55     testemptypara(4,5)
    56     testjustlog(3,4)
    View Code
     1 Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:22:17) [MSC v.1500 32 bit (Intel)] on win32
     2 Type "copyright", "credits" or "license()" for more information.
     3 >>> 
     4 ============ RESTART: D:pytestlogdecorator.py ============
     5 before called! 2
     6 lisa
     7 50
     8 x*y=30
     9 after called! 2
    10 email=lisa@xxx.com
    11 --------------------
    12 before called! 0
    13 x*y=20
    14 after called! 0
    15 --------------------
    16 before called! 0
    17 x*y=12
    18 after called! 0
    19 --------------------
    20 >>> 
    test result
  • 相关阅读:
    ClickHouse
    SparkSql运行原理详细解析
    Hive优化一
    低代码平台,到底能给企业带来什么?
    观点:BPM已经过时了?
    一个好产品,只是帮用户做好了一件事
    高科技电子行业的信息化怎么做?
    【重要!】告K2老客户书
    移动互联网公司如何将BPM流程管理变身移动化?
    BPM业务流程管理与SAP如何更好集成整合?
  • 原文地址:https://www.cnblogs.com/zftylj/p/pythonlog.html
Copyright © 2011-2022 走看看