import os
import time
import logging

def get_logger(name, level='INFO'):
    format = '%(name)s %(message)s'
    datefmt = None
    # turn off log time stamps if NOTIME is non-empty
    if os.getenv('GUARD_LOG_NOTIME', '') == '':
        format = '%(asctime)s.%(msecs)03dZ ' + format
        # time in ISO 8601 format
        # https://en.wikipedia.org/wiki/ISO_8601
        datefmt = '%Y-%m-%dT%H:%M:%S'
    # log level definitions:
    # CRITICAL: messages associated with guard termination
    # ERROR   :
    # WARNING : *** used for operator comments ***
    # INFO    : standard logging
    # DEBUG   : debugging
    # MULTI   : DEBUG + multiprocessing logging enabled
    loglevel = os.getenv('GUARD_LOG_LEVEL', level).upper()
    if loglevel == 'MULTI':
        loglevel = 'DEBUG'
        import multiprocessing
        multiprocessing.log_to_stderr().setLevel('DEBUG')
    logging.addLevelName(5, 'LOOP')
    logger = logging.getLogger(name)
    logger.setLevel(loglevel)
    formatter = logging.Formatter(format, datefmt=datefmt)
    if datefmt:
        formatter.converter = time.gmtime
    ch = logging.StreamHandler()
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    return logger

# FIXME: use SocketHandler to collect and serialize logs from worker subprocess
# http://docs.python.org/2/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes

class StateLogger(logging.LoggerAdapter):
    def __init__(self, logger, state=None):
        super(StateLogger, self).__init__(logger, {'state': state})
        self.extra['state'] = ''
        self.extra['func'] = ''

    def set_state(self, state):
        self.extra['state'] = state

    def set_func(self, func):
        self.extra['func'] = func

    def process(self, msg, kwargs):
        msg = '[%s.%s] %s' % (self.extra['state'], self.extra['func'], msg)
        return (msg, kwargs)
