# Copyright (c) ZhangYundi.
# Licensed under the MIT License. 
# Created on 2025/7/18 20:28
# Description:

from loguru import logger
import sys
from pathlib import Path


logger.remove()
# 设置全局异常捕获
def handle_exception(exc_type, exc_value, exc_traceback):
    """全局异常处理函数"""
    logger.opt(exception=(exc_type, exc_value, exc_traceback)).critical(
        "Unhandled exception occurred"
    )

sys.excepthook = handle_exception

def patch_name(record):
    record["extra"].setdefault("name", "?")

logger = logger.patch(patch_name)

console_format = (
    "<lvl>{level:.1} {time:YYYY-MM-DD HH:mm:ss}</lvl> | "
    "<lvl>{extra[name]: <15}</lvl> | "
    "<bold><green>{process}:{thread.name}</green></bold> | "
    "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
    "<lvl>{message}</lvl>"
)


logger.add(
    sys.stderr,
    format=console_format,
    level="TRACE"
)

logs_dir = Path("logs")
logs_dir.mkdir(exist_ok=True)

logger.add(
    logs_dir / "{time:YYYYMMDD}.log",
    retention="10 days",
    format=console_format,
    level="TRACE"
)

def get_logger(name):
    return logger.bind(name=name)