Skip to content

Instantly share code, notes, and snippets.

@dioptx
Created March 24, 2019 13:17
Show Gist options
  • Save dioptx/0804bf8b270b3044ba646fa1f3bd3936 to your computer and use it in GitHub Desktop.
Save dioptx/0804bf8b270b3044ba646fa1f3bd3936 to your computer and use it in GitHub Desktop.
import logging
from logging.handlers import RotatingFileHandler
import inspect
def create_rotating_log():
'''
Creates a rotating logger function
:return:
'''
logger = logging.getLogger(_settings.Name)
logger.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# add a rotating handler
# create file handler which logs even debug messages
fh = logging.handlers.RotatingFileHandler('app.log', maxBytes=5000,
backupCount=4)
fh.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
return logger
logger = create_rotating_log()
def log_name(f):
@wraps(f)
def wrapper(*args, **kwds):
logger.info('Calling: {0}'.format(f.__name__))
return f(*args,**kwds)
return wrapper
@log_name
def a_function():
print('do stuff')
try:
print('do_tricky_stuff')
except Exception as ex:
logger.exception('Function {0} : {1}'.format(inspect.getframeinfo(inspect.currentframe()).function, ex))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment