Method of python Using Decorator for Log Processing

  • 2021-07-16 02:47:00
  • OfStack

I looked at the decorator for a while to understand that there is a layer of function outside the function, which feels very similar to the aop function in java; I wrote two examples of decorator logs,

The first is an example of decorator usage without parameters, which is equivalent to wrapping a function with layer exception handling, and the second is an example of decorator usage with parameters, which outputs logs to files.


```
#coding=utf8
import traceback
import logging
from logging.handlers import TimedRotatingFileHandler
def logger(func):
 def inner(*args, **kwargs): #1
 try:
  #print "Arguments were: %s, %s" % (args, kwargs)
  func(*args, **kwargs) #2
 except:
  #print 'error',traceback.format_exc()
  print 'error'
 return inner


def loggerInFile(filename):# Decorators with parameters require 2 Layer decorator implementation , No. 1 1 Layer transfer parameter, first 2 Layer transfer function, each layer function is on 1 Layer return 
 def decorator(func):
 def inner(*args, **kwargs): #1
  logFilePath = filename #  The log is scrolled by date and retained 5 Days 
  logger = logging.getLogger()
  logger.setLevel(logging.INFO)
  handler = TimedRotatingFileHandler(logFilePath,
       when="d",
       interval=1,
       backupCount=5)
  formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  handler.setFormatter(formatter)
  logger.addHandler(handler)
  try:
  #print "Arguments were: %s, %s" % (args, kwargs)
  result = func(*args, **kwargs) #2
  logger.info(result)
  except:
  logger.error(traceback.format_exc())
 return inner
 return decorator

@logger
def test():
 print 2/0

test()


@loggerInFile('newloglog')
def test2(n):
 print 100/n

test2(10)
test2(0)
print 'end'
```

Related articles: