2016-07-25 20:04:30 +02:00
|
|
|
import logging
|
|
|
|
import logging.handlers
|
|
|
|
import sys
|
|
|
|
|
|
|
|
|
|
|
|
DEFAULT_FORMAT = "%(asctime)s %(levelname)-8s %(name)s:%(lineno)d: %(message)s"
|
|
|
|
DEFAULT_FORMATTER = logging.Formatter(DEFAULT_FORMAT)
|
|
|
|
|
|
|
|
|
2016-08-08 21:57:49 +02:00
|
|
|
def remove_handlers(log, handler_name):
|
|
|
|
for handler in log.handlers:
|
|
|
|
if handler.name == handler_name:
|
|
|
|
log.removeHandler(handler)
|
|
|
|
|
|
|
|
|
|
|
|
def _log_decorator(fn):
|
|
|
|
def helper(*args, **kwargs):
|
|
|
|
log = kwargs.pop('log', logging.getLogger())
|
|
|
|
level = kwargs.pop('level', logging.INFO)
|
|
|
|
handler = fn(*args, **kwargs)
|
|
|
|
if handler.name:
|
|
|
|
remove_handlers(log, handler.name)
|
|
|
|
log.addHandler(handler)
|
|
|
|
log.setLevel(level)
|
|
|
|
return helper
|
|
|
|
|
|
|
|
|
|
|
|
@_log_decorator
|
|
|
|
def configure_console(**kwargs):
|
2016-07-25 20:04:30 +02:00
|
|
|
"""Convenience function to configure a logger that outputs to stdout"""
|
|
|
|
handler = logging.StreamHandler(sys.stdout)
|
|
|
|
handler.setFormatter(DEFAULT_FORMATTER)
|
2016-08-08 21:57:49 +02:00
|
|
|
handler.name = 'console'
|
|
|
|
return handler
|
2016-07-25 20:04:30 +02:00
|
|
|
|
|
|
|
|
2016-08-08 21:57:49 +02:00
|
|
|
@_log_decorator
|
|
|
|
def configure_file_handler(file_name, **kwargs):
|
2016-07-25 20:04:30 +02:00
|
|
|
handler = logging.handlers.RotatingFileHandler(file_name, maxBytes=2097152, backupCount=5)
|
|
|
|
handler.setFormatter(DEFAULT_FORMATTER)
|
2016-08-08 21:57:49 +02:00
|
|
|
handler.name = 'file'
|
|
|
|
return handler
|