# -*- coding:utf-8 -*-
"""
@author: yq
@time: 2022/8/29
@desc:
"""

import datetime
import logging
import logging.handlers
import os
import threading
import time
from os.path import dirname, realpath

import pytz

from commom.traceId_util import TraceIdFilter


def my_time(*args):
    return time.strptime(datetime.datetime.now(pytz.timezone("Asia/Shanghai")).strftime("%Y-%m-%d %H:%M:%S"),
                         "%Y-%m-%d %H:%M:%S")


_instance_lock = threading.Lock()
logger_map = {}


def get_logger(logger_name: str = None) -> logging.Logger:
    if logger_name is None:
        logger_name = "app"
    if logger_name in logger_map.keys():
        return logger_map.get(logger_name)
    with _instance_lock:
        if logger_name in logger_map.keys():
            return logger_map.get(logger_name)

        _logger = logging.Logger(logger_name)
        _logger.setLevel(logging.INFO)
        _logger.addFilter(TraceIdFilter())

        formatter = logging.Formatter(
            '[%(asctime)s] [requestId-%(requestId)s] [%(levelname)s] [%(threadName)s] [%(filename)s] [func:%(funcName)s line:%(lineno)d]\n %(message)s')
        formatter.converter = my_time

        log_path = os.path.join(dirname(dirname(realpath(__file__))), "logs")
        filename = os.path.join(log_path, f"{logger_name}.log")

        if not os.path.exists(dirname(filename)):
            os.makedirs(dirname(filename))
        print(f"日志路径：{filename}")

        handler = logging.handlers.TimedRotatingFileHandler(filename, when="MIDNIGHT", interval=7, backupCount=4,
                                                            encoding="utf8", atTime=datetime.time(0, 0, 0, 0))
        handler.setFormatter(formatter)
        _logger.addHandler(handler)

        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        _logger.addHandler(console_handler)

        logger_map[logger_name] = _logger

        return _logger
