File size: 1,378 Bytes
c481f8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import os
import sys
from pathlib import Path

from loguru import logger

_configured_log_path: Path | None = None


def configure_logging(storage_dir: Path) -> Path:
    global _configured_log_path

    logs_dir = (storage_dir / "logs").resolve()
    logs_dir.mkdir(parents=True, exist_ok=True)
    log_path = logs_dir / "service.log"

    if _configured_log_path == log_path:
        return log_path
    _configured_log_path = log_path

    level = (os.getenv("LOG_LEVEL") or "INFO").strip().upper()
    rotation = (os.getenv("LOG_ROTATION") or "1 day").strip()
    retention = (os.getenv("LOG_RETENTION") or "14 days").strip()
    compression = (os.getenv("LOG_COMPRESSION") or "zip").strip()
    fmt = "{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} - {message} | {extra}"

    logger.remove()
    logger.add(
        sys.stderr,
        level=level,
        format=fmt,
        enqueue=True,
        backtrace=False,
        diagnose=False,
    )
    logger.add(
        str(log_path),
        level=level,
        format=fmt,
        enqueue=True,
        backtrace=False,
        diagnose=False,
        rotation=rotation,
        retention=retention,
        compression=compression,
    )

    logger.info(f"logging_initialized path={log_path} rotation={rotation} retention={retention}")
    return log_path