File size: 1,886 Bytes
c4e128a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Loguru logging configuration for the KDC project."""

from __future__ import annotations

import sys
from pathlib import Path

from loguru import logger


def setup_logging(
    level: str = "INFO",
    sink_file: Path | None = None,
    rotation: str = "10 MB",
    retention: str = "30 days",
    *,
    colorize: bool = True,
) -> None:
    """
    Configure Loguru sinks.

    Always adds a stderr sink.
    Optionally adds a rotating file sink when sink_file is provided.
    """
    # Remove the default Loguru handler
    logger.remove()

    # ── Console sink ──────────────────────────────────────────────────────────
    logger.add(
        sys.stderr,
        level=level.upper(),
        colorize=colorize,
        format=(
            "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
            "<level>{level: <8}</level> | "
            "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> — "
            "<level>{message}</level>"
        ),
    )

    # ── File sink ─────────────────────────────────────────────────────────────
    if sink_file is not None:
        sink_file.parent.mkdir(parents=True, exist_ok=True)
        logger.add(
            str(sink_file),
            level=level.upper(),
            rotation=rotation,
            retention=retention,
            encoding="utf-8",
            format=(
                "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | " "{name}:{function}:{line} — {message}"
            ),
        )


def get_logger(name: str) -> logger:  # type: ignore[valid-type]
    """Return a bound Loguru logger with a module context."""
    return logger.bind(name=name)