|
1 | 1 | import { tmpdir } from 'os'; |
2 | | -import { writeFileSync } from 'fs'; |
| 2 | +import { existsSync, renameSync, writeFileSync } from 'fs'; |
| 3 | +import { basename, dirname, join } from 'path'; |
3 | 4 |
|
4 | 5 | interface LogEntry { |
5 | 6 | type: 'info' | 'error'; |
6 | 7 | timestamp: number; |
7 | 8 | message: string; |
8 | 9 | } |
9 | 10 |
|
| 11 | +const LATEST_TAG = 'latest'; |
| 12 | +const OLD_TAG = 'old'; |
| 13 | + |
10 | 14 | export class LoggerService { |
11 | 15 | private log: LogEntry[] = []; |
12 | 16 |
|
@@ -44,12 +48,23 @@ export class LoggerService { |
44 | 48 | return log + line; |
45 | 49 | }, ''); |
46 | 50 |
|
| 51 | + this.rotateLogFile(path); |
47 | 52 | writeFileSync(path, content); |
48 | 53 | } |
49 | 54 |
|
50 | 55 | getSuggestLogfilePath(): string { |
51 | | - const timestamp = new Date().getTime(); |
52 | | - return `${tmpdir()}/npkill-${timestamp}.log`; |
| 56 | + return `${tmpdir()}/npkill-${LATEST_TAG}.log`; |
| 57 | + } |
| 58 | + |
| 59 | + private rotateLogFile(newLogPath: string): void { |
| 60 | + if (!existsSync(newLogPath)) { |
| 61 | + return; // Rotation is not necessary |
| 62 | + } |
| 63 | + const basePath = dirname(newLogPath); |
| 64 | + const logName = basename(newLogPath); |
| 65 | + const oldLogName = logName.replace(LATEST_TAG, OLD_TAG); |
| 66 | + const oldLogPath = join(basePath, oldLogName); |
| 67 | + renameSync(newLogPath, oldLogPath); |
53 | 68 | } |
54 | 69 |
|
55 | 70 | private addToLog(entry: LogEntry): void { |
|
0 commit comments