Files
cmbot/src/services/log_service.py
T

57 lines
1.7 KiB
Python
Raw Normal View History

2026-06-15 15:53:01 +08:00
import logging
import os
from datetime import datetime
2026-06-15 15:53:01 +08:00
def setup_logging(log_dir=None):
"""Initialize file + console logging. Call once at application startup.
log_dir: str or Path to log directory. Defaults to <app_dir>/logs/ via
file_service.get_log_dir(). Falls back to console-only if the
directory cannot be created.
"""
if log_dir is None:
try:
from services.file_service import get_log_dir
log_dir = get_log_dir()
except OSError as exc:
_setup_console_only()
logging.getLogger(__name__).warning(
"Cannot create log directory: %s. Falling back to console only.", exc
)
return
else:
try:
os.makedirs(str(log_dir), exist_ok=True)
except OSError as exc:
_setup_console_only()
logging.getLogger(__name__).warning(
"Cannot create log directory %s: %s. Falling back to console only.", log_dir, exc
)
return
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
log_file = os.path.join(str(log_dir), "app_{}.log".format(timestamp))
formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")
root = logging.getLogger()
root.setLevel(logging.INFO)
fh = logging.FileHandler(log_file, encoding="utf-8")
fh.setFormatter(formatter)
root.addHandler(fh)
sh = logging.StreamHandler()
sh.setFormatter(formatter)
root.addHandler(sh)
logging.getLogger(__name__).info("Logging initialized. Log file: %s", log_file)
def _setup_console_only():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(name)s %(levelname)s %(message)s",
)