MCPcopy Create free account
hub / github.com/Tron521/codex-console-temp / cleanup_database_logs

Function cleanup_database_logs

src/core/db_logs.py:111–164  ·  view source on GitHub ↗

清理后台日志: 1) 删除超过 retention_days 的日志 2) 若总量超过 max_rows,删除最旧的超量部分

(
    retention_days: Optional[int] = None,
    max_rows: int = 50000,
)

Source from the content-addressed store, hash-verified

109
110
111def 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 }

Callers 1

cleanup_logsFunction · 0.85

Calls 9

get_settingsFunction · 0.85
utcnow_naiveFunction · 0.85
get_dbFunction · 0.85
scalarMethod · 0.80
countMethod · 0.80
allMethod · 0.80
deleteMethod · 0.45
filterMethod · 0.45
queryMethod · 0.45

Tested by

no test coverage detected