Files
chunyu_project/logs/tasks.py
T
2026-08-05 23:59:15 +08:00

62 lines
1.9 KiB
Python

from celery import shared_task
from django.utils import timezone
from datetime import timedelta
@shared_task
def cleanup_old_request_logs():
threshold = timezone.now() - timedelta(days=30)
from .models import ApiRequestLog
deleted_count, _ = ApiRequestLog.objects.filter(timestamp__lt=threshold).delete()
return f'已清理 {deleted_count} 条过期请求日志'
@shared_task
def cleanup_old_error_logs():
threshold = timezone.now() - timedelta(days=90)
from .models import ErrorLog
deleted_count, _ = ErrorLog.objects.filter(
timestamp__lt=threshold,
is_resolved=True
).delete()
return f'已清理 {deleted_count} 条已处理的过期错误日志'
@shared_task
def cleanup_old_event_logs():
threshold = timezone.now() - timedelta(days=60)
from .models import SystemEventLog
deleted_count, _ = SystemEventLog.objects.filter(timestamp__lt=threshold).delete()
return f'已清理 {deleted_count} 条过期事件日志'
@shared_task
def generate_daily_stats():
from .models import ApiRequestLog, ErrorLog
from django.db.models import Count, Avg
today_start = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
yesterday_start = today_start - timedelta(days=1)
yesterday_stats = ApiRequestLog.objects.filter(
timestamp__gte=yesterday_start,
timestamp__lt=today_start
).aggregate(
total_requests=Count('id'),
error_count=Count('id', filter={'is_error': True}),
avg_duration=Avg('duration_ms'),
)
error_count = ErrorLog.objects.filter(
timestamp__gte=yesterday_start,
timestamp__lt=today_start
).count()
return {
'date': yesterday_start.date().isoformat(),
'total_requests': yesterday_stats['total_requests'],
'error_requests': yesterday_stats['error_count'],
'error_logs': error_count,
'avg_duration_ms': round(yesterday_stats['avg_duration'] or 0, 2),
}