#!/usr/bin/python

# Python library with logging related functions

import sys
import logging
import logging.handlers
import socket
import time

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)


def add_handler_file(tag_name, file_log_name, max_bytes, backup_count):
    '''
    Add a handler to rotating file to given logger
    '''
    file_handler = logging.handlers.RotatingFileHandler(filename=file_log_name, maxBytes=max_bytes, backupCount=backup_count)
    file_handler.setFormatter(get_formatter(tag_name))

    # Log into rotating file in appfs
    logger.addHandler(file_handler)


def add_handler_stdout(tag_name, stream=sys.stdout):
    '''
    Add a handler to stdout to given logger
    '''
    console_handler = logging.StreamHandler(stream)
    console_handler.setFormatter(get_formatter(tag_name))

    # Log to stream
    logger.addHandler(console_handler)


def add_handler_syslog(tag_name):
    '''
    Add a handler to syslog to given logger
    '''
    syslog_handler = logging.handlers.SysLogHandler(address='/dev/log')
    syslog_handler.setFormatter(get_formatter(tag_name))

    # Log to syslog
    logger.addHandler(syslog_handler)


def log_header(msg, *args, **kwargs):
    """
    Add a header to the logs
    """    
    line = "*" * (len(msg)+4)

    logger.info(line)
    logger.info("* " + msg + " *", *args, **kwargs)
    logger.info(line)


# Aug 17 12:59:21 [tag_name]: [log] ||| <module> in test.py:30
def get_formatter(tag_name):
    '''
    Get logging formatter
    '''

    formatter = logging.Formatter("%(asctime)s @name@: %(message)s ||| %(funcName)s in %(filename)s:%(lineno)d".replace("@name@", tag_name),'%b %d %H:%M:%S')
    # Use UTC time for logger
    formatter.converter = time.gmtime

    return formatter
