# coding:utf-8
import os
import logging
import time
import logging.config
from log_conf import conf

"""
class Log(object):
    def __init__(self):
        # 配置
        logging.config.dictConfig(conf)

    def __console(self, level, message):
        if level == 'info':
            logger = logging.getLogger('sls')
            logger.info(message)
        elif level == 'debug':
            logger = logging.getLogger('root')
            logger.debug(message)
        elif level == 'warning':
            logger = logging.getLogger('root')
            logger.warning(message)
        elif level == 'error':
            logger = logging.getLogger('error')
            logger.error(message)

    def debug(self, message):
        self.__console('debug', message)

    def info(self, message):
        self.__console('info', message)

    def warning(self, message):
        self.__console('warning', message)

    def error(self, message):
        self.__console('error', message)
"""


class Log(object):
    # def __init__(self, pag_source, log_path=os.path.join(os.path.dirname(os.path.realpath(__file__)), "logs")):
    def __init__(self, log_path=os.path.join(os.path.dirname(os.path.realpath(__file__)), "logs")):
        if not os.path.exists(log_path):
            os.makedirs(log_path)

        # 文件的命名
        # self.logname = os.path.join(log_path, '{}_{}.log'.format(pag_source, time.strftime('%Y%m%d')))
        self.logname = os.path.join(log_path, '{}.log'.format(time.strftime('%Y%m%d')))
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)
        # 日志输出格式
        self.formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
        # self.formatter = logging.Formatter('%(asctime)s [%(filename)s] %(levelname)s: %(message)s')

    def __console(self, level, message):
        # 创建一个FileHandler，用于写到本地
        fh = logging.FileHandler(self.logname, 'a', encoding='utf-8')
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(self.formatter)
        self.logger.addHandler(fh)

        # 创建一个StreamHandler,用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(self.formatter)
        self.logger.addHandler(ch)

        if level == 'info':
            self.logger.info(message)
        elif level == 'debug':
            self.logger.debug(message)
        elif level == 'warning':
            self.logger.warning(message)
        elif level == 'error':
            self.logger.error(message)
        # 这两行代码是为了避免日志输出重复问题
        self.logger.removeHandler(ch)
        self.logger.removeHandler(fh)
        # 关闭打开的文件
        fh.close()

    def debug(self, message):
        self.__console('debug', message)

    def info(self, message):
        self.__console('info', message)

    def warning(self, message):
        self.__console('warning', message)

    def error(self, message):
        self.__console('error', message)
