mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-09-17 23:51:19 +00:00
- Added log_to_file parameter to Application class constructor - Integrated log_to_file option in logger initialization - Updated ServiceContext to support file logging configuration - Modified init_logger function to conditionally enable file logging - Added log_to_file field to ServiceConfig schema - Updated ReMe class to include file logging option - Wrapped file logging setup in conditional check to prevent unnecessary operations
59 lines
2 KiB
Python
59 lines
2 KiB
Python
"""Logging configuration module for application-wide tracing."""
|
|
|
|
import os
|
|
import sys
|
|
from datetime import datetime
|
|
|
|
|
|
def init_logger(
|
|
log_dir: str = "logs",
|
|
level: str = "INFO",
|
|
log_to_console: bool = True,
|
|
log_to_file: bool = True,
|
|
) -> None:
|
|
"""Initialize the logger with both file and console handlers.
|
|
|
|
Args:
|
|
log_dir: Directory path for log files
|
|
level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
|
log_to_console: Whether to print logs to console/screen
|
|
log_to_file: Whether to persist logs to files under log_dir
|
|
"""
|
|
from loguru import logger
|
|
|
|
# Remove default handler to avoid duplicate logs
|
|
logger.remove()
|
|
|
|
# Configure colorized standard output logging if enabled
|
|
if log_to_console:
|
|
logger.add(
|
|
sink=sys.stdout,
|
|
level=level,
|
|
format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {file}:{line} | {function} | {message}",
|
|
colorize=True,
|
|
)
|
|
|
|
# Try to configure file-based logging (skip if permission denied)
|
|
if log_to_file:
|
|
try:
|
|
# Ensure the logging directory exists
|
|
os.makedirs(log_dir, exist_ok=True)
|
|
|
|
# Generate filename based on the current timestamp
|
|
# Use dashes instead of colons for Windows compatibility
|
|
current_ts = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
|
log_filename = f"{current_ts}.log"
|
|
log_filepath = os.path.join(log_dir, log_filename)
|
|
|
|
# Configure file-based logging with rotation and compression
|
|
logger.add(
|
|
log_filepath,
|
|
level=level,
|
|
rotation="00:00",
|
|
retention="7 days",
|
|
compression="zip",
|
|
encoding="utf-8",
|
|
format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {file}:{line} | {function} | {message}",
|
|
)
|
|
except Exception as e:
|
|
logger.error(f"Error configuring file logging: {e}")
|