Open History to see the last commit
1import fs from "node:fs";
2import path from "node:path";
3
4export interface RotatingFileSinkOptions {
5 readonly filePath: string;
6 readonly maxBytes: number;
7 readonly maxFiles: number;
8 readonly throwOnError?: boolean;
9}
10
11export class RotatingFileSink {
12 private readonly filePath: string;
13 private readonly maxBytes: number;
14 private readonly maxFiles: number;
15 private readonly throwOnError: boolean;
16 private currentSize = 0;
17
18 constructor(options: RotatingFileSinkOptions) {
19 if (options.maxBytes < 1) {
20 throw new Error(`maxBytes must be >= 1 (received ${options.maxBytes})`);
21 }
22 if (options.maxFiles < 1) {
23 throw new Error(`maxFiles must be >= 1 (received ${options.maxFiles})`);
24 }
25
26 this.filePath = options.filePath;
27 this.maxBytes = options.maxBytes;
28 this.maxFiles = options.maxFiles;
29 this.throwOnError = options.throwOnError ?? false;
30
31 fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
32 this.pruneOverflowBackups();
33 this.currentSize = this.readCurrentSize();
34 }
35
36 write(chunk: string | Buffer): void {
37 const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
38 if (buffer.length === 0) return;
39
40 try {
41 if (this.currentSize > 0 && this.currentSize + buffer.length > this.maxBytes) {
42 this.rotate();
43 }
44
45 fs.appendFileSync(this.filePath, buffer);
46 this.currentSize += buffer.length;
47
48 if (this.currentSize > this.maxBytes) {
49 this.rotate();
50 }
51 } catch {
52 this.currentSize = this.readCurrentSize();
53 if (this.throwOnError) {
54 throw new Error(`Failed to write log chunk to ${this.filePath}`);
55 }
56 }
57 }
58
59 private rotate(): void {
60 try {
61 const oldest = this.withSuffix(this.maxFiles);
62 if (fs.existsSync(oldest)) {
63 fs.rmSync(oldest, { force: true });
64 }
65
66 for (let index = this.maxFiles - 1; index >= 1; index -= 1) {
67 const source = this.withSuffix(index);
68 const target = this.withSuffix(index + 1);
69 if (fs.existsSync(source)) {
70 fs.renameSync(source, target);
71 }
72 }
73
74 if (fs.existsSync(this.filePath)) {
75 fs.renameSync(this.filePath, this.withSuffix(1));
76 }
77
78 this.currentSize = 0;
79 } catch {
80 this.currentSize = this.readCurrentSize();
81 if (this.throwOnError) {
82 throw new Error(`Failed to rotate log file ${this.filePath}`);
83 }
84 }
85 }
86
87 private pruneOverflowBackups(): void {
88 try {
89 const dir = path.dirname(this.filePath);
90 const baseName = path.basename(this.filePath);
91 for (const entry of fs.readdirSync(dir)) {
92 if (!entry.startsWith(`${baseName}.`)) continue;
93 const suffix = Number(entry.slice(baseName.length + 1));
94 if (!Number.isInteger(suffix) || suffix <= this.maxFiles) continue;
95 fs.rmSync(path.join(dir, entry), { force: true });
96 }
97 } catch {
98 if (this.throwOnError) {
99 throw new Error(`Failed to prune log backups for ${this.filePath}`);
100 }
101 }
102 }
103
104 private readCurrentSize(): number {
105 try {
106 return fs.statSync(this.filePath).size;
107 } catch {
108 return 0;
109 }
110 }
111
112 private withSuffix(index: number): string {
113 return `${this.filePath}.${index}`;
114 }
115}