
import logging
import logging.handlers
from logging.handlers import RotatingFileHandler
import inspect

infraLogger = None

def initLogger(logPath, logLevel = logging.INFO, logMaxBytes = 4 * 1024 * 1024, logBackupCount = 3):
    logger = logging.getLogger("InfraLogger")
    logger.setLevel(logLevel)

    formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] [%(wfilename)s:%(wfuncName)s:%(wlineno)d] %(message)s ')

    handler = RotatingFileHandler(
            filename=logPath,
            maxBytes=logMaxBytes,
            backupCount=logBackupCount
            )

    handler.setFormatter(formatter)

    if logger.handlers:
        logger.handlers = []

    logger.addHandler(handler)

    global infraLogger
    infraLogger = logger



def debug(*args):
    frame = inspect.stack()[1]
    filename = frame[1]
    lineno = frame[2]
    funcname = frame[3]

    message = " ".join([str(x) for x in args])
    extra = {
            'wfilename': filename,
            'wlineno': lineno, 
            'wfuncName': funcname
    }

    infraLogger.debug(message, extra = extra)

def info(*args):
    frame = inspect.stack()[1]
    dir(frame)
    filename = frame[1]
    lineno = frame[2]
    funcname = frame[3]

    message = " ".join([str(x) for x in args])
    extra = {
            'wfilename': filename,
            'wlineno': lineno, 
            'wfuncName': funcname
    }

    infraLogger.info(message, extra = extra)

def error(*args):
    frame = inspect.stack()[1]
    filename = frame[1]
    lineno = frame[2]
    funcname = frame[3]

    message = " ".join([str(x) for x in args])
    extra = {
            'wfilename': filename,
            'wlineno': lineno, 
            'wfuncName': funcname
    }
    print extra
    print message

    infraLogger.error(message, extra = extra)


def example_function():
    for i in range(0, 1000000000000000000000000000000):
        info("This is an INFO message from example_function.")
        error("This is an ERROR message from example_function.")
        debug("This is a DEBUG message.")


initLogger("./test.log")
example_function()

