Wrapper and logging

import sys

import logging

import os


logging.basicConfig(level=logging.INFO,

handlers=[logging.StreamHandler()],

format='%(asctime)s,%(name)s,%(levelname)s,%(message)s')

logger = logging.getLogger(os.path.basename(__file__))


from functools import wraps

def catch_exception(origin_func):

@wraps(origin_func)

def wrapper(self, *args, **kwargs):

try:

self.logger.info(origin_func.__name__ + ',pre')

u = origin_func(self, *args, **kwargs)

self.logger.info(origin_func.__name__ + ',post')

return u

except Exception as e:

self.logger.error(origin_func.__name__ + ',error,' + repr(e))

sys.exit()

finally:

self.logger.info(origin_func.__name__ + ',end')

return wrapper



class test_wrapper:

def __init__(self):

self.logger = self._generate_logger()

def __str__(self):

msg = "test_wrapper"

return msg

def _generate_logger(self):

logging.basicConfig(level=logging.INFO,

handlers=[logging.StreamHandler()],

format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

return logging.getLogger(str(self))

@catch_exception

def test_wrapper_function_success(self):

self.logger.info('test_wrapper_function_success')

@catch_exception

def test_wrapper_function_fail(self):

self.logger.info('test_wrapper_function_fail')

x = 1

y = x / 0

if __name__ == "__main__":

logger.info('start')

new_test_wrapper = test_wrapper()

new_test_wrapper.test_wrapper_function_success()

logger.info('finish test_wrapper_function_success')

new_test_wrapper.test_wrapper_function_fail()

logger.info('finish test_wrapper_function_fail')

Result