79 lines
2.8 KiB
Python
Raw Normal View History

2025-01-23 23:12:52 +02:00
import logging
import os
from logging.handlers import RotatingFileHandler
from datetime import datetime
class AlarmLogger:
def __init__(self, log_dir='logs', log_level=logging.INFO):
"""
Initialize a comprehensive logging system for the alarm application.
Args:
log_dir (str): Directory to store log files
log_level (int): Logging level (default: logging.INFO)
"""
# Ensure log directory exists
os.makedirs(log_dir, exist_ok=True)
# Create a unique log filename with timestamp
log_filename = os.path.join(
log_dir,
f"alarm_app_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
)
# Configure the root logger
logging.basicConfig(
level=log_level,
format='%(asctime)s | %(levelname)8s | %(module)15s:%(lineno)4d | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# Create rotating file handler
file_handler = RotatingFileHandler(
log_filename,
maxBytes=10*1024*1024, # 10 MB
backupCount=5
)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s | %(levelname)8s | %(module)15s:%(lineno)4d | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
))
# Create console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(
'%(levelname)8s | %(module)15s:%(lineno)4d | %(message)s'
))
# Get the root logger and add handlers
root_logger = logging.getLogger()
root_logger.addHandler(file_handler)
root_logger.addHandler(console_handler)
self.logger = logging.getLogger(__name__)
def log_alarm_created(self, alarm_details):
"""Log alarm creation details."""
self.logger.info(f"Alarm Created: {alarm_details}")
def log_alarm_triggered(self, alarm_id):
"""Log when an alarm is triggered."""
self.logger.warning(f"Alarm Triggered: ID {alarm_id}")
def log_alarm_snoozed(self, alarm_id, snooze_duration):
"""Log alarm snooze details."""
self.logger.info(f"Alarm Snoozed: ID {alarm_id}, Duration: {snooze_duration} minutes")
def log_system_error(self, error_message, exc_info=False):
"""Log system errors with optional exception details."""
self.logger.error(error_message, exc_info=exc_info)
def log_api_interaction(self, method, endpoint, status):
"""Log API interactions."""
self.logger.info(f"API {method.upper()}: {endpoint} - Status: {status}")
# Example usage in other modules
# logger = AlarmLogger()
# logger.log_alarm_created({"time": "07:00", "repeat": "daily"})
# logger.log_system_error("Failed to connect to API", exc_info=True)