Skip to content

Commit b9dd681

Browse files
committed
refactor(logger): change to log rotation
1 parent 2050084 commit b9dd681

1 file changed

Lines changed: 18 additions & 3 deletions

File tree

src/services/logger.service.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
import { tmpdir } from 'os';
2-
import { writeFileSync } from 'fs';
2+
import { existsSync, renameSync, writeFileSync } from 'fs';
3+
import { basename, dirname, join } from 'path';
34

45
interface LogEntry {
56
type: 'info' | 'error';
67
timestamp: number;
78
message: string;
89
}
910

11+
const LATEST_TAG = 'latest';
12+
const OLD_TAG = 'old';
13+
1014
export class LoggerService {
1115
private log: LogEntry[] = [];
1216

@@ -44,12 +48,23 @@ export class LoggerService {
4448
return log + line;
4549
}, '');
4650

51+
this.rotateLogFile(path);
4752
writeFileSync(path, content);
4853
}
4954

5055
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);
5368
}
5469

5570
private addToLog(entry: LogEntry): void {

0 commit comments

Comments
 (0)