|
| 1 | +import { fileManagerService } from "@/infrastructure/services/file-manager/file-manager.service"; |
| 2 | +import { existsSync, stat, unlink, writeFileSync } from "fs"; |
| 3 | + |
| 4 | +const logCleaningInterval: number = 120000 |
| 5 | +let timeout: NodeJS.Timeout | undefined; |
| 6 | + |
| 7 | +export async function cleanLogs( |
| 8 | + maxFileSizeBytes?: number | undefined, |
| 9 | + daysToKeep?: number | undefined, |
| 10 | +): Promise<void> { |
| 11 | + // clear existing timeout |
| 12 | + // in case we rerun it with different values |
| 13 | + if (timeout) clearTimeout(timeout) |
| 14 | + timeout = undefined |
| 15 | + |
| 16 | + |
| 17 | + console.log( |
| 18 | + 'Validating app logs. Next attempt in ', |
| 19 | + logCleaningInterval |
| 20 | + ) |
| 21 | + |
| 22 | + const size = maxFileSizeBytes ?? 1 * 1024 * 1024 // 1 MB |
| 23 | + const days = daysToKeep ?? 7 // 7 days |
| 24 | + const filePath = await fileManagerService.getLogPath() |
| 25 | + // Perform log cleaning |
| 26 | + const currentDate = new Date() |
| 27 | + if (existsSync(filePath)) |
| 28 | + stat(filePath, (err, stats) => { |
| 29 | + if (err) { |
| 30 | + console.error('Error getting file stats:', err) |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + // Check size |
| 35 | + if (stats.size > size) { |
| 36 | + writeFileSync(filePath, '', 'utf8') |
| 37 | + } else { |
| 38 | + // Check age |
| 39 | + const creationDate = new Date(stats.ctime) |
| 40 | + const daysDifference = Math.floor( |
| 41 | + (currentDate.getTime() - creationDate.getTime()) / |
| 42 | + (1000 * 3600 * 24) |
| 43 | + ) |
| 44 | + if (daysDifference > days) { |
| 45 | + writeFileSync(filePath, '', 'utf8') |
| 46 | + } |
| 47 | + } |
| 48 | + }) |
| 49 | + |
| 50 | + // Schedule the next execution with doubled delays |
| 51 | + timeout = setTimeout( |
| 52 | + () => this.cleanLogs(maxFileSizeBytes, daysToKeep), |
| 53 | + logCleaningInterval |
| 54 | + ) |
| 55 | +} |
0 commit comments