- LoggingService.findLogs(): the `to` date filter compared a date-only string (e.g. from a date picker) against a timestamp column, which parses to midnight and silently excludes the entire last day. Widen it to end-of-day so the range is genuinely inclusive. - LogRetentionScheduler.cleanupOldLogs(): wrap the delete in try/catch and log failures via logger.error, matching the existing convention in CashboxExportScheduler/RecurringTransactionsScheduler. Without this, a failed nightly cleanup would fail silently - exactly what this feature exists to prevent. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
42 lines
1.4 KiB
TypeScript
42 lines
1.4 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { Cron, CronExpression } from '@nestjs/schedule';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { LessThan, Repository } from 'typeorm';
|
|
import { LogEntry } from './entities/log-entry.entity';
|
|
import { LoggingService } from './logging.service';
|
|
|
|
@Injectable()
|
|
export class LogRetentionScheduler {
|
|
constructor(
|
|
@InjectRepository(LogEntry)
|
|
private readonly repository: Repository<LogEntry>,
|
|
private readonly configService: ConfigService,
|
|
private readonly logger: LoggingService,
|
|
) {}
|
|
|
|
@Cron(CronExpression.EVERY_DAY_AT_4AM)
|
|
async cleanupOldLogs(): Promise<void> {
|
|
const retentionDays = this.configService.get<number>('app.logRetentionDays');
|
|
const cutoff = new Date();
|
|
cutoff.setUTCDate(cutoff.getUTCDate() - retentionDays);
|
|
|
|
try {
|
|
const result = await this.repository.delete({ createdAt: LessThan(cutoff) });
|
|
|
|
await this.logger.info({
|
|
event: 'log_retention_cleanup_run',
|
|
details: `deletedCount=${result.affected ?? 0} retentionDays=${retentionDays}`,
|
|
userId: -1,
|
|
});
|
|
} catch (error) {
|
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
await this.logger.error({
|
|
event: 'log_retention_cleanup_run_fail',
|
|
details: errorMessage,
|
|
userId: -1,
|
|
});
|
|
}
|
|
}
|
|
}
|