# -*- coding: utf-8 -*-
# @Time    : 2024/5/16
# @Author  : 魏志亮

import logging
import logging.handlers
import os


# 日志配置函数化，避免全局副作用
def setup_logger(log_path: str = "/data/logs"):
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    # 避免重复添加handler
    if logger.handlers:
        return logger

    os.makedirs(log_path, exist_ok=True)

    # 1. 创建并配置TimedRotatingFileHandler（所有级别的文件输出）
    all_log_handler = logging.handlers.TimedRotatingFileHandler(
        os.path.join(log_path, "info.log"), 'D', backupCount=90
    )

    # 2. 创建并配置ERROR级别的TimedRotatingFileHandler
    error_log_handler = logging.handlers.TimedRotatingFileHandler(
        os.path.join(log_path, "error.log"), 'D', backupCount=90
    )
    error_log_handler.setLevel(logging.ERROR)

    # 3. 创建并配置StreamHandler（控制台输出）
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)

    # 定义日志格式
    fmt = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s",
        "%Y-%m-%d %H:%M:%S"
    )

    # 设置各个handler的格式
    all_log_handler.setFormatter(fmt)
    error_log_handler.setFormatter(fmt)
    console_handler.setFormatter(fmt)

    # 添加handler
    logger.addHandler(all_log_handler)
    logger.addHandler(error_log_handler)
    logger.addHandler(console_handler)

    return logger


logger = setup_logger("/home/trans/project/logs/")
