feat: auto-cleanup logs older than 7 days
Request logs and reaction logs are automatically pruned on each request
via waitUntil. Zero-cost async cleanup, no cron needed.
小橘 🍊(NEKO Team)
This commit is contained in:
parent
cc9f3eb88f
commit
8702e8b1c3
@ -79,26 +79,33 @@ app.use('*', async (c, next) => {
|
||||
if (path === '/health' || path.startsWith('/ui')) return
|
||||
|
||||
try {
|
||||
const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000
|
||||
const cutoff = Date.now() - SEVEN_DAYS_MS
|
||||
c.executionCtx.waitUntil(
|
||||
c.env.DB.prepare(
|
||||
'INSERT INTO request_logs (method, path, api_key_id, api_key_name, status_code, error, duration_ms, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
)
|
||||
.bind(
|
||||
c.req.method,
|
||||
path,
|
||||
c.get('apiKeyId') || null,
|
||||
c.get('apiKeyName') || null,
|
||||
c.res.status,
|
||||
c.res.status >= 400
|
||||
? await c.res
|
||||
.clone()
|
||||
.text()
|
||||
.catch(() => null)
|
||||
: null,
|
||||
duration,
|
||||
Date.now(),
|
||||
Promise.all([
|
||||
c.env.DB.prepare(
|
||||
'INSERT INTO request_logs (method, path, api_key_id, api_key_name, status_code, error, duration_ms, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
)
|
||||
.run(),
|
||||
.bind(
|
||||
c.req.method,
|
||||
path,
|
||||
c.get('apiKeyId') || null,
|
||||
c.get('apiKeyName') || null,
|
||||
c.res.status,
|
||||
c.res.status >= 400
|
||||
? await c.res
|
||||
.clone()
|
||||
.text()
|
||||
.catch(() => null)
|
||||
: null,
|
||||
duration,
|
||||
Date.now(),
|
||||
)
|
||||
.run(),
|
||||
// Cleanup logs older than 7 days
|
||||
c.env.DB.prepare('DELETE FROM request_logs WHERE created_at < ?').bind(cutoff).run(),
|
||||
c.env.DB.prepare('DELETE FROM reaction_logs WHERE created_at < ?').bind(cutoff).run(),
|
||||
]),
|
||||
)
|
||||
} catch {
|
||||
// executionCtx not available in test, skip
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user