from loguru import logger
import os
import socket

from huibiao_framework.backend.log_utils import LogSetup, LogCleaner
from huibiao_framework.config.config import LogConfig


class ServiceLoggerManager:
    """
    容器内日志目录默认是：/logger/服务名
    """

    @classmethod
    def service_log_dir(cls, service_name: str):
        return os.path.join(LogConfig.LOGGER_PATH, service_name)

    @classmethod
    def setup_log(cls, service_name: str):
        """
        日志设置
        """

        LogSetup.rotate_daily(
            log_dir=cls.service_log_dir(service_name),
            service_name=cls.add_container_id(service_name=service_name),
            add_pid_suffix=True,
            save_info=LogConfig.SAVE_INFO_LEVEL,
            save_debug=LogConfig.SAVE_DEBUG_LOG,
        )

        for pkg in LogConfig.get_disable_log_pkg():
            # 忽略一些包的日志
            logger.debug(f"ignore log: {pkg}")
            logger.disable(pkg)

    @classmethod
    def run_log_cleaner(cls, service_name: str):
        """
        启动定时任务清理日志
        """
        LogCleaner.schedule_run(
            log_dir=cls.service_log_dir(service_name=service_name), retention_day=LogConfig.LOG_RETENTION_DAY
        )

    @classmethod
    def add_container_id(cls, service_name: str):
        if not LogConfig.LOG_ADD_CONTAINED_ID:
            logger.info("日志名不增加containerId")
            return service_name

        try:
            socket_hostname = f"-{socket.gethostname()}"
        except:
            socket_hostname = ""
        if service_name in socket_hostname:
            return service_name
        else:
            return f"{service_name}{socket_hostname}"
