Case:
Implements an adorner that logs function call information to a log
Requirements:
- Writes the call time of each function, execution time, and number of calls to the log
- Can be grouped by decorated functions, call information logging to different logs
- Dynamic modification of parameters, such as log format
- Dynamic Turn off log output feature
How to solve this problem?
For the flexibility of the adorner, define a decoration class, the instance method of this class as the adorner, in the class adorner method holds the instance object, facilitates the modification property and the extension function
#!/usr/bin/python3import loggingfrom Time Import time, strftime, localtime, Sleepfrom random import choicefrom functools i Mport Wrapsclass Tolog (): Def __init__ (self, name): Log = Logging.getlogger (name) log.setlevel (logging. INFO) # Log Save file name file_name = logging. Filehandler (name + '. Log ') # Add log file Log.addhandler (file_name) # Log Format log.info (' Start '. Center (5 0, '-')) Self.log = log self.temp = '% (func) s-and [% (start_time) s-% (used_time) s-% (naclls) s] ' De F Go_log (Self, func): @wraps (func) def wrapper (*args, **kwargs): # function per call plus 1 WRAPPER.N Aclls + = 1 start_time = time () res = func (*args, **kwargs) Used_time = time () -Start_time info = {} info[' func '] = func.__name__ info[' start_time '] = STA Rt_time info[' used_time '] = used_time info[' naclls '] = Wrapper.naclls msg = self.temp% Info # writes the log in format to file Self.log.info (msg) Retu RN Res # Initialize number of calls parameter Wrapper.naclls = 0 Return wrapper # Redefine the logging template def set_l Og_temp (Self, temp): self.temp = temp # shutdown log function def log_off (self): Self.log.setLevel (logging. WARN) # Open log function Def log_on (self): Self.log.setLevel (logging.info) # Instantiate two adorner object log_one = Tolog (' one ') log_tw o = Tolog (' double ') # modifies the log template for instance 2, removing the execution time log_two.set_log_temp ('% (func) s-and [% (start_time) s-% (naclls) s] ') # Close Log_ The logging function in both Log_two.log_off () @log_one. Go_logdef func_one (): Print (' one ') @log_one. Go_logdef func_two (): Print (' Both ') @log_two. Go_logdef func_three (): Print (' three ') if __name__ = = ' __main__ ': for _ in Range: Choice ([func_ One, Func_two, Func_three]) () Sleep (choice ([0.5, 1, 1.5]))
Python_ How to define adorners in a class