# import logging
# from logging.handlers import TimedRotatingFileHandler
# import os
# import sys
#
# from configs.config import LOG_NAME, LOG_PATH, LOG_STDERR, LOG_LEVEL
#
# DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S'
# DEFAULT_FORMAT = '[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] %(message)s'
# LOGGING_MAPPING = {}
#
#
# def get_logging(name=None, file_name=None) -> logging.Logger:
#     """
#     获取日志对象
#     :param name:
#     :param file_name:
#     :return:
#     """
#     global LOGGING_MAPPING
#     name = str(name) if name else 'default'
#     file_name = str(file_name) if file_name else LOG_NAME
#     log_key = ('%s_%s' % (name, file_name)).replace('.', '_')
#     if log_key not in LOGGING_MAPPING.keys():
#         _generate_logger(name, file_name)
#     return LOGGING_MAPPING.get(log_key)
#
#
# def _generate_logger(name=None, file_name=None):
#     """
#     创建日志对象
#     :param name:
#     :param file_name:
#     :return:
#     """
#     global LOGGING_MAPPING
#     final_log_name = file_name if file_name else LOG_NAME
#     log_file = os.path.join(LOG_PATH, final_log_name)
#     channel_handler = TimedRotatingFileHandler(filename=log_file, when='MIDNIGHT', backupCount=30)
#     channel_handler.setFormatter(logging.Formatter(DEFAULT_FORMAT, datefmt=DEFAULT_DATE_FORMAT))
#
#     logger = logging.getLogger(name if name else 'default')
#     logger.addHandler(channel_handler)
#
#     if LOG_STDERR:
#         stream_channel = logging.StreamHandler(sys.stderr)
#         stream_channel.setFormatter(logging.Formatter(DEFAULT_FORMAT))
#         logger.addHandler(stream_channel)
#     logger.setLevel(LOG_LEVEL)
#     LOGGING_MAPPING[('%s_%s' % (name, file_name)).replace('.', '_')] = logger


import time
import logging
import os
import socket
from datetime import datetime, timezone, timedelta

from configs.config import LOG_PATH

hostname = socket.gethostname()
current_directory = os.path.dirname(os.path.abspath(__file__))

def create_time_today():
    utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
    create_time = utc_dt.astimezone(timezone(timedelta(hours=8)))
    return create_time

def get_current_time():
    current_time = create_time_today().strftime('%Y-%m-%d')  # 返回当前时间
    return current_time


class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }
    count = 0

    def __init__(self,
                 fmt="[%(asctime)s] [%(process)d] [%(levelname)s] - %(module)s.%(funcName)s (%(filename)s:%(lineno)d) - %(message)s"):
        self.current_time = get_current_time()
        self.format_str = logging.Formatter(fmt)  # 设置日志格式
        self.create_handler()
        Logger.count += 1

    def create_handler(self):
        self.current_time = get_current_time()
        filename = LOG_PATH + 'operation' + "-" + get_current_time() + '.log'
        self.logger = logging.getLogger(filename)
        self.logger.setLevel(logging.INFO)  # 设置日志级别
        if not self.logger.handlers:
            sh = logging.StreamHandler()
            sh.setFormatter(self.format_str)
            th = logging.FileHandler(filename=filename, encoding='utf-8')
            th.setFormatter(self.format_str)  # 设置文件里写入的格式
            self.logger.addHandler(sh)  # 把对象加到logger里
            self.logger.addHandler(th)

    def info(self, msg):
        current_time = get_current_time()
        if self.current_time != current_time:
            self.create_handler()

        self.logger.info(msg)
        print("有{}个日志打印类对象".format(Logger.count))
        return

    def warning(self, msg):
        current_time = get_current_time()
        if self.current_time != current_time:
            self.create_handler()
        self.logger.warning(msg)
        return

    def error(self, msg):
        current_time = get_current_time()
        if self.current_time != current_time:
            self.create_handler()

        self.logger.error(msg)
        return
