import { Injectable, Logger } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; import { PrismaService } from '../prisma/prisma.service'; import { SettingsService } from '../settings/settings.service'; // 查询日志保留周期清理:每天凌晨执行,删除超过保留天数的日志。 // 保留天数取系统设置 logRetentionDays(后台可配置),<=0 表示长期保留、不清理。 @Injectable() export class LogRetentionService { private readonly logger = new Logger(LogRetentionService.name); constructor( private readonly prisma: PrismaService, private readonly settings: SettingsService, ) {} @Cron(CronExpression.EVERY_DAY_AT_3AM) async cleanup(): Promise { const days = await this.resolveRetentionDays(); if (!days || days <= 0) { this.logger.log('日志保留周期为长期保留,跳过清理'); return; } const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000); const { count } = await this.prisma.queryLog.deleteMany({ where: { queriedAt: { lt: cutoff } }, }); this.logger.log(`查询日志清理完成:删除 ${count} 条(保留 ${days} 天,截止 ${cutoff.toISOString()})`); } private async resolveRetentionDays(): Promise { const raw = await this.settings.get('logRetentionDays'); const n = Number(raw); if (raw !== null && !Number.isNaN(n)) return n; return 365; } }