# -*- coding:utf-8 -*-

import os
import logging
from logging import FileHandler
import time

class SafeFileHandler(FileHandler):
    """solve multi-process write file problems"""
    def __init__(self, filename, mode, encoding=None, delay=0):
        """
        Use the specified filename for streamed logging
        """
        FileHandler.__init__(self, filename, mode, encoding, delay)
        self.mode = mode
        self.encoding = encoding
        self.suffix = "%Y%m%d"
        self.suffix_time = ""

    def emit(self, record):
        """
        Emit a record.

        Always check time
        """
        try:
            if self.check_baseFilename(record):
                self.build_baseFilename()
            FileHandler.emit(self, record)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

    def check_baseFilename(self, record):
        """
        Determine if builder should occur.

        record is not used, as we are just comparing times,
        but it is needed so the method signatures are the same
        """
        timeTuple = time.localtime()

        if self.suffix_time != time.strftime(self.suffix, timeTuple) or not os.path.exists(self.baseFilename+'.'+self.suffix_time):
            return 1
        else:
            return 0

    def build_baseFilename(self):
        """
        do builder; in this case,
        old time stamp is removed from filename and
        a new time stamp is append to the filename
        """
        if self.stream:
            self.stream.close()
            self.stream = None

        # remove old suffix
        if self.suffix_time != "":
            index = self.baseFilename.find("."+self.suffix_time)
            if index == -1:
                index = self.baseFilename.rfind(".")
            self.baseFilename = self.baseFilename[:index]

        # add new suffix
        currentTimeTuple = time.localtime()
        self.suffix_time = time.strftime(self.suffix, currentTimeTuple)
        self.baseFilename  = self.baseFilename + "." + self.suffix_time

        self.mode = 'a'
        if not self.delay:
            self.stream = self._open()


def setlogger(config):
    cfg = config
    logger = logging.getLogger("QAsearch")
    formatter = logging.Formatter(cfg['LogFormat'])
    logger.setLevel(10)
    # setup console setting
    if cfg['LogLevel_Console'] != 0:
        ch = logging.StreamHandler()
        ch.setLevel(cfg["LogLevel_Console"])
        ch.setFormatter(formatter)
        logger.addHandler(ch)
    # setup file logging path
    if cfg['LogLevel_File'] != 0:
        folder = cfg['LogFile']
        if not os.path.exists(os.path.dirname(folder)):
            os.makedirs(os.path.dirname(folder), exist_ok=True)
        fh = SafeFileHandler(folder, mode='a')
        fh.setLevel(cfg["LogLevel_File"])
        fh.setFormatter(formatter)
        logger.addHandler(fh)

logger = logging.getLogger("QAsearch")

if __name__ == '__main__':
    config = {}
    logger = setlogger(config)
    text = input("input print info:")
    logger.info(text)
    logger.warning("it worked")
