# Logging supporting functions
#
# Copyright (C) 2011 Michal Kajan, Libor Polčák, Petr Kramoliš
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging
import sys
import time
from traceback import format_tb

LEVELS = {'debug': logging.DEBUG,
          'info': logging.INFO,
          'warning': logging.WARNING,
          'error': logging.ERROR,
          'critical': logging.CRITICAL}

def setupLogging(argVector):
    if len(argVector) > 0:
        levelName = argVector[0]
    else:
        levelName = ""
    level = LEVELS.get(levelName, logging.ERROR)
    logging.basicConfig(level=level)
    # Force child loggers to respect console logging settings
    logging.root.handlers[0].setLevel(level)
    logging.debug("Logging level set to %d" % level)

def emptyMessageHandler(msg):
    logging.debug("%s: Empty handler for %s" % (sys.argv[0], str(msg)))

def createFileLogger(loggerName, fileName, rowFormat="%(asctime)s %(message)s"):
    """ Create file logger
    
    loggerName Name of the logger
    fileName Name of the file where to store the log
    rowFormat String specifing format of the log, see python
    documentation for more details
    """
    logger = logging.getLogger(loggerName)
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter(rowFormat)
    fh = logging.FileHandler(fileName)
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    return logger

def createFileLoggerPlain(loggerName, fileName):
    """ Create file logger without time information"""
    return createFileLogger(loggerName, fileName, "%(message)s")

def transformArgs(args):
    return "%s: %s: %s" % (time.strftime("%d.%m.%Y %H:%M:%S"), sys.argv[0], str(" ".join([str(a) for a in args])))

def debug(*args):
    logging.debug(transformArgs(args))

def info(*args):
    logging.info(transformArgs(args))

def warning(*args):
    logging.warning(transformArgs(args))

def error(*args):
    logging.error(transformArgs(args))

def critical(*args):
    logging.critical(transformArgs(args))

def unhandledException(begining, e):
    """ Logs information about unhandled exception
    
    begining String that should be displayed in the beginning
    e The exception
    """
    t = str(e.__class__)[8:-2]
    msg = str(e)
    traceback = format_tb(e.__traceback__)
    critical(begining, t, msg)
    for l in traceback:
        critical(begining, l[:-1])

