清理后台日志: 1) 删除超过 retention_days 的日志 2) 若总量超过 max_rows,删除最旧的超量部分
(
retention_days: Optional[int] = None,
max_rows: int = 50000,
)
| 109 | |
| 110 | |
| 111 | def cleanup_database_logs( |
| 112 | retention_days: Optional[int] = None, |
| 113 | max_rows: int = 50000, |
| 114 | ) -> Dict[str, Any]: |
| 115 | """ |
| 116 | 清理后台日志: |
| 117 | 1) 删除超过 retention_days 的日志 |
| 118 | 2) 若总量超过 max_rows,删除最旧的超量部分 |
| 119 | """ |
| 120 | settings = get_settings() |
| 121 | keep_days = int(retention_days if retention_days is not None else settings.log_retention_days or 30) |
| 122 | keep_days = max(1, keep_days) |
| 123 | max_rows = max(1000, int(max_rows)) |
| 124 | cutoff = utcnow_naive() - timedelta(days=keep_days) |
| 125 | |
| 126 | deleted_by_age = 0 |
| 127 | deleted_by_limit = 0 |
| 128 | |
| 129 | with get_db() as db: |
| 130 | deleted_by_age = ( |
| 131 | db.query(AppLog) |
| 132 | .filter(AppLog.created_at < cutoff) |
| 133 | .delete(synchronize_session=False) |
| 134 | ) |
| 135 | db.commit() |
| 136 | |
| 137 | total = db.query(func.count(AppLog.id)).scalar() or 0 |
| 138 | if total > max_rows: |
| 139 | overflow = int(total - max_rows) |
| 140 | overflow_ids = [ |
| 141 | row_id |
| 142 | for (row_id,) in db.query(AppLog.id) |
| 143 | .order_by(AppLog.created_at.asc(), AppLog.id.asc()) |
| 144 | .limit(overflow) |
| 145 | .all() |
| 146 | ] |
| 147 | if overflow_ids: |
| 148 | deleted_by_limit = ( |
| 149 | db.query(AppLog) |
| 150 | .filter(AppLog.id.in_(overflow_ids)) |
| 151 | .delete(synchronize_session=False) |
| 152 | ) |
| 153 | db.commit() |
| 154 | |
| 155 | remaining = db.query(func.count(AppLog.id)).scalar() or 0 |
| 156 | |
| 157 | return { |
| 158 | "retention_days": keep_days, |
| 159 | "max_rows": max_rows, |
| 160 | "deleted_by_age": int(deleted_by_age or 0), |
| 161 | "deleted_by_limit": int(deleted_by_limit or 0), |
| 162 | "deleted_total": int((deleted_by_age or 0) + (deleted_by_limit or 0)), |
| 163 | "remaining": int(remaining or 0), |
| 164 | } |
no test coverage detected