|
1 | | -import { createReadStream } from 'fs'; |
2 | | -import { join } from 'path'; |
| 1 | +import { createReadStream, existsSync, stat, writeFileSync } from 'fs'; |
3 | 2 | import { createInterface } from 'readline'; |
| 3 | +import { fileManagerService } from '@/infrastructure/services/file-manager/file-manager.service'; |
| 4 | + |
| 5 | +const logCleaningInterval: number = 120000; |
| 6 | +let timeout: NodeJS.Timeout | undefined; |
4 | 7 |
|
5 | 8 | /** |
6 | 9 | * Print the last N lines of a file that contain the word 'ERROR' |
@@ -30,3 +33,48 @@ export async function printLastErrorLines( |
30 | 33 | errorLines.forEach((line) => console.log(line)); |
31 | 34 | console.log('...'); |
32 | 35 | } |
| 36 | + |
| 37 | +export async function cleanLogs( |
| 38 | + maxFileSizeBytes?: number | undefined, |
| 39 | + daysToKeep?: number | undefined, |
| 40 | +): Promise<void> { |
| 41 | + // clear existing timeout |
| 42 | + // in case we rerun it with different values |
| 43 | + if (timeout) clearTimeout(timeout); |
| 44 | + timeout = undefined; |
| 45 | + |
| 46 | + console.log('Validating app logs. Next attempt in ', logCleaningInterval); |
| 47 | + |
| 48 | + const size = maxFileSizeBytes ?? 1 * 1024 * 1024; // 1 MB |
| 49 | + const days = daysToKeep ?? 7; // 7 days |
| 50 | + const filePath = await fileManagerService.getLogPath(); |
| 51 | + // Perform log cleaning |
| 52 | + const currentDate = new Date(); |
| 53 | + if (existsSync(filePath)) |
| 54 | + stat(filePath, (err, stats) => { |
| 55 | + if (err) { |
| 56 | + console.error('Error getting file stats:', err); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + // Check size |
| 61 | + if (stats.size > size) { |
| 62 | + writeFileSync(filePath, '', 'utf8'); |
| 63 | + } else { |
| 64 | + // Check age |
| 65 | + const creationDate = new Date(stats.ctime); |
| 66 | + const daysDifference = Math.floor( |
| 67 | + (currentDate.getTime() - creationDate.getTime()) / (1000 * 3600 * 24), |
| 68 | + ); |
| 69 | + if (daysDifference > days) { |
| 70 | + writeFileSync(filePath, '', 'utf8'); |
| 71 | + } |
| 72 | + } |
| 73 | + }); |
| 74 | + |
| 75 | + // Schedule the next execution with doubled delays |
| 76 | + timeout = setTimeout( |
| 77 | + () => this.cleanLogs(maxFileSizeBytes, daysToKeep), |
| 78 | + logCleaningInterval, |
| 79 | + ); |
| 80 | +} |
0 commit comments