import logging
import sys


class JSONAwareLogFormatter(logging.Formatter):
    def format(self, record):
        record.message = record.getMessage()
        if self.usesTime():
            record.asctime = self.formatTime(record, self.datefmt)
        return self._fmt % record.__dict__


class LoggerFactory(object):
    def __init__(self, level, name=None, formatter=None, **kwargs):
        self._name = name or 'glogger'
        self._fmt = formatter or JSONAwareLogFormatter(kwargs.get('fmt'))
        self._handlers = kwargs.get('handlers') or []
        self._level = level or logging.INFO
        self._stream = kwargs.get('stream') or sys.stdout
        self._logger = None

    def __call__(self, *args, **kwargs):
        if not self._logger:
            self._init_logger()
        return self._logger

    def _init_logger(self):
        sh = logging.StreamHandler(stream=self._stream)
        sh.setFormatter(self._fmt)

        logger = logging.getLogger(self._name)
        logger.setLevel(self._level)
        logger.propagate = False
        logger.addHandler(sh)
        for h in self._handlers:
            logger.addHandler(h)
        self._logger = logger
