Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

logging.ts

182 lines5.0 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4import * as Schema from "effect/Schema";
5​
6export interface RotatingFileSinkOptions {
7 readonly filePath: string;
8 readonly maxBytes: number;
9 readonly maxFiles: number;
10 readonly throwOnError?: boolean;
12​
13export class RotatingFileSinkConfigurationError extends Schema.TaggedErrorClass<RotatingFileSinkConfigurationError>()(
14 "RotatingFileSinkConfigurationError",
15 {
16 option: Schema.Literals(["maxBytes", "maxFiles"]),
17 received: Schema.Number,
18 minimum: Schema.Number,
19 },
20) {
21 override get message(): string {
22 return `${this.option} must be >= ${this.minimum} (received ${this.received})`;
23 }
25​
26export class RotatingFileSinkError extends Schema.TaggedErrorClass<RotatingFileSinkError>()(
27 "RotatingFileSinkError",
28 {
29 operation: Schema.Literals(["initialize", "read", "write", "rotate", "prune"]),
30 filePath: Schema.String,
31 cause: Schema.Defect(),
32 },
33) {
34 override get message(): string {
35 return `Failed to ${this.operation} rotating log file ${this.filePath}`;
36 }
38​
39const isRotatingFileSinkError = Schema.is(RotatingFileSinkError);
40​
41const isFileNotFoundError = (cause: unknown): cause is NodeJS.ErrnoException =>
42 cause instanceof Error && "code" in cause && cause.code === "ENOENT";
43​
44export class RotatingFileSink {
45 private readonly filePath: string;
46 private readonly maxBytes: number;
47 private readonly maxFiles: number;
48 private readonly throwOnError: boolean;
49 private currentSize = 0;
50​
51 constructor(options: RotatingFileSinkOptions) {
52 if (options.maxBytes < 1) {
53 throw new RotatingFileSinkConfigurationError({
54 option: "maxBytes",
55 received: options.maxBytes,
56 minimum: 1,
57 });
58 }
59 if (options.maxFiles < 1) {
60 throw new RotatingFileSinkConfigurationError({
61 option: "maxFiles",
62 received: options.maxFiles,
63 minimum: 1,
64 });
65 }
66​
67 this.filePath = options.filePath;
68 this.maxBytes = options.maxBytes;
69 this.maxFiles = options.maxFiles;
70 this.throwOnError = options.throwOnError ?? false;
71​
72 try {
73 NodeFS.mkdirSync(NodePath.dirname(this.filePath), { recursive: true });
74 } catch (cause) {
75 throw new RotatingFileSinkError({
76 operation: "initialize",
77 filePath: this.filePath,
78 cause,
79 });
80 }
81 this.pruneOverflowBackups();
82 this.currentSize = this.readCurrentSize();
83 }
84​
85 write(chunk: string | Buffer): void {
86 const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
87 if (buffer.length === 0) return;
88​
89 try {
90 if (this.currentSize > 0 && this.currentSize + buffer.length > this.maxBytes) {
91 this.rotate();
92 }
93​
94 NodeFS.appendFileSync(this.filePath, buffer);
95 this.currentSize += buffer.length;
96 } catch (cause) {
97 if (isRotatingFileSinkError(cause)) {
98 throw cause;
99 }
100 if (this.throwOnError) {
101 throw new RotatingFileSinkError({
102 operation: "write",
103 filePath: this.filePath,
104 cause,
105 });
106 }
107 this.currentSize = this.readCurrentSize();
108 }
109 }
110​
111 private rotate(): void {
112 try {
113 const oldest = this.withSuffix(this.maxFiles);
114 if (NodeFS.existsSync(oldest)) {
115 NodeFS.rmSync(oldest, { force: true });
116 }
117​
118 for (let index = this.maxFiles - 1; index >= 1; index -= 1) {
119 const source = this.withSuffix(index);
120 const target = this.withSuffix(index + 1);
121 if (NodeFS.existsSync(source)) {
122 NodeFS.renameSync(source, target);
123 }
124 }
125​
126 if (NodeFS.existsSync(this.filePath)) {
127 NodeFS.renameSync(this.filePath, this.withSuffix(1));
128 }
129​
130 this.currentSize = 0;
131 } catch (cause) {
132 if (this.throwOnError) {
133 throw new RotatingFileSinkError({
134 operation: "rotate",
135 filePath: this.filePath,
136 cause,
137 });
138 }
139 this.currentSize = this.readCurrentSize();
140 }
141 }
142​
143 private pruneOverflowBackups(): void {
144 try {
145 const dir = NodePath.dirname(this.filePath);
146 const baseName = NodePath.basename(this.filePath);
147 for (const entry of NodeFS.readdirSync(dir)) {
148 if (!entry.startsWith(`${baseName}.`)) continue;
149 const suffix = Number(entry.slice(baseName.length + 1));
150 if (!Number.isInteger(suffix) || suffix <= this.maxFiles) continue;
151 NodeFS.rmSync(NodePath.join(dir, entry), { force: true });
152 }
153 } catch (cause) {
154 if (this.throwOnError) {
155 throw new RotatingFileSinkError({
156 operation: "prune",
157 filePath: this.filePath,
158 cause,
159 });
160 }
161 }
162 }
163​
164 private readCurrentSize(): number {
165 try {
166 return NodeFS.statSync(this.filePath).size;
167 } catch (cause) {
168 if (isFileNotFoundError(cause)) {
169 return 0;
170 }
171 throw new RotatingFileSinkError({
172 operation: "read",
173 filePath: this.filePath,
174 cause,
175 });
176 }
177 }
178​
179 private withSuffix(index: number): string {
180 return `${this.filePath}.${index}`;
181 }