Files
digiserver-v2/app/utils/logger.py
ske087 53ab7fa4ab Add models and utils with type hints and optimizations
Models (6 + 1 association table):
- User: Authentication with bcrypt, admin role check, last_login tracking
- Player: Digital signage devices with auth codes, status tracking, online detection
- Group: Player/content organization with statistics properties
- Content: Media files with type detection, file size helpers, position ordering
- ServerLog: Audit trail with class methods for logging levels
- PlayerFeedback: Player status updates with error tracking
- group_content: Many-to-many association table for groups and content

Model improvements:
- Added type hints to all methods and properties
- Added database indexes on frequently queried columns (username, auth_code, group_id, player_id, position, level, timestamp, status)
- Added comprehensive docstrings
- Added helper properties (is_online, is_admin, file_size_mb, etc.)
- Added relationship back_populates for bidirectional navigation
- Added timestamps (created_at, updated_at, last_seen, uploaded_at)

Utils (4 modules):
- logger.py: Logging utility with level-based functions (info, warning, error)
- uploads.py: File upload handling with progress tracking, video optimization
- group_player_management.py: Player/group status tracking and bulk operations
- pptx_converter.py: PowerPoint to PDF conversion using LibreOffice

Utils improvements:
- Full type hints on all functions
- Comprehensive error handling
- Progress tracking for long-running operations
- Video optimization (H.264, 30fps, max 1080p, 8Mbps)
- Helper functions for time formatting and statistics
- Proper logging of all operations

Performance optimizations:
- Database indexes on all foreign keys and frequently filtered columns
- Lazy loading for relationships where appropriate
- Efficient queries with proper ordering
- Helper properties to avoid repeated calculations

Ready for template migration and testing
2025-11-12 10:26:19 +02:00

79 lines
2.1 KiB
Python

"""Logging utility for tracking system events."""
from typing import Optional
from datetime import datetime, timedelta
from app.extensions import db
from app.models.server_log import ServerLog
def log_action(level: str, message: str) -> None:
"""Log an action to the database with specified level.
Args:
level: Log level (info, warning, error)
message: Log message content
"""
try:
new_log = ServerLog(level=level, message=message)
db.session.add(new_log)
db.session.commit()
print(f"[{level.upper()}] {message}")
except Exception as e:
print(f"Error logging action: {e}")
db.session.rollback()
def get_recent_logs(limit: int = 20, level: Optional[str] = None) -> list:
"""Get the most recent log entries.
Args:
limit: Maximum number of logs to return
level: Optional filter by log level
Returns:
List of ServerLog instances
"""
query = ServerLog.query
if level:
query = query.filter_by(level=level)
return query.order_by(ServerLog.timestamp.desc()).limit(limit).all()
def clear_old_logs(days: int = 30) -> int:
"""Delete logs older than specified days.
Args:
days: Number of days to keep
Returns:
Number of logs deleted
"""
try:
cutoff_date = datetime.utcnow() - timedelta(days=days)
deleted = ServerLog.query.filter(ServerLog.timestamp < cutoff_date).delete()
db.session.commit()
log_action('info', f'Deleted {deleted} old log entries (older than {days} days)')
return deleted
except Exception as e:
db.session.rollback()
print(f"Error clearing old logs: {e}")
return 0
# Convenience functions for specific log levels
def log_info(message: str) -> None:
"""Log an info level message."""
log_action('info', message)
def log_warning(message: str) -> None:
"""Log a warning level message."""
log_action('warning', message)
def log_error(message: str) -> None:
"""Log an error level message."""
log_action('error', message)