# synarere -- a trivial, highly modular IRC bot.
# Copyright (C) 2010 Michael Rodriguez.
# Rights to this code are documented in ../docs/LICENSE.

'''Logger facility.'''

# Import required Python module.
import logging
from logging import handlers

# Import required source modules.
import instance, var

# Make these references to the real methods.
debug, info, warning, error, critical = None, None, None, None, None

def get_level():
    '''Get the logging level.'''

    if instance.conf.get('logger', 'level')[0] == 'info':
        return logging.INFO
    elif instance.conf.get('logger', 'level')[0] == 'warning':
        return logging.WARNING
    elif instance.conf.get('logger', 'level')[0] == 'debug':
        return logging.DEBUG
    elif instance.conf.get('logger', 'level')[0] == 'error':
        return logging.ERROR
    elif instance.conf.get('logger', 'level')[0] == 'critical':
        return logging.CRITICAL

def init():
    """Initialise the logging subsystem."""

    global debug, info, warning, error, critical

    instance.log = logging.getLogger('synarere')

    # Set up logging to stderr if we're in foreground mode.
    if not var.fork:
        stream = logging.StreamHandler()
    else:
        stream = None

    handler = handlers.RotatingFileHandler(filename=instance.conf.get('logger', 'path')[0], maxBytes=instance.conf.get('logger', 'max_size')[0], backupCount=instance.conf.get('logger', 'max_logs')[0])
    formatter = logging.Formatter(instance.conf.get('logger', 'format')[0])

    handler.setFormatter(formatter)

    if stream:
        stream_format = logging.Formatter(instance.conf.get('logger', 'stream_format')[0])
        stream.setFormatter(stream_format)
        instance.log.addHandler(stream)

    instance.log.addHandler(handler)
    instance.log.setLevel(get_level())

    debug, info, warning = instance.log.debug, instance.log.info, instance.log.warning
    error, critical = instance.log.error, instance.log.critical
