@loglayer/transport-log-file-rotation 2.1.6 → 2.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,374 +1,340 @@
1
- // src/LogFileRotationTransport.ts
2
- import { createReadStream, createWriteStream, writeFileSync } from "fs";
3
- import { access, unlink } from "fs/promises";
4
- import { pipeline } from "stream/promises";
5
- import { createGzip } from "zlib";
1
+ import { createReadStream, createWriteStream, writeFileSync } from "node:fs";
2
+ import { access, unlink } from "node:fs/promises";
3
+ import { pipeline } from "node:stream/promises";
4
+ import { createGzip } from "node:zlib";
6
5
  import { LoggerlessTransport } from "@loglayer/transport";
7
6
  import FileStreamRotator from "file-stream-rotator";
8
- var LogFileRotationTransport = class _LogFileRotationTransport extends LoggerlessTransport {
9
- /** Registry of active filenames to prevent multiple transports writing to the same file */
10
- static activeFilenames = /* @__PURE__ */ new Set();
11
- /** The current write stream for the log file */
12
- stream;
13
- /** Custom field names for log entries */
14
- fieldNames;
15
- /** Delimiter between log entries */
16
- delimiter;
17
- /** Function to generate timestamps for log entries */
18
- timestampFn;
19
- /** Custom mapping for log levels */
20
- levelMap;
21
- /** Whether to compress rotated files */
22
- compressOnRotate;
23
- /** Whether a file is currently being compressed */
24
- isCompressing;
25
- /** The base filename pattern for log files */
26
- filename;
27
- /** Static data to be included in every log entry */
28
- staticData;
29
- /** Whether batch processing is enabled */
30
- batchEnabled;
31
- /** Maximum number of log entries to queue before writing */
32
- batchSize;
33
- /** Maximum time in milliseconds to wait before writing queued logs */
34
- batchTimeout;
35
- /** Queue of log entries waiting to be written */
36
- batchQueue;
37
- /** Timer for batch flush timeout */
38
- batchTimer;
39
- /** Whether the transport is being disposed */
40
- isDisposing;
41
- /** Event callbacks for various file stream events */
42
- callbacks;
43
- /** Frequency of rotation (daily, hourly, etc.) */
44
- frequency;
45
- /** Whether to enable verbose mode */
46
- verbose;
47
- /** Date format for filename patterns */
48
- dateFormat;
49
- /** Size threshold for rotation */
50
- size;
51
- /** Maximum number of log files to keep */
52
- maxLogs;
53
- /** Path to the audit file */
54
- auditFile;
55
- /** File extension for log files */
56
- extension;
57
- /** Whether to create a symlink to current log */
58
- createSymlink;
59
- /** Name of the symlink file */
60
- symlinkName;
61
- /** Whether to use UTC time in filenames */
62
- utc;
63
- /** Hash algorithm for audit file */
64
- auditHashType;
65
- /** Options for file streams */
66
- fileOptions;
67
- /** File mode to be used when creating log files */
68
- fileMode;
69
- /**
70
- * Generates the options for FileStreamRotator consistently across the transport
71
- * @returns FileStreamRotatorOptions object
72
- * @private
73
- */
74
- getRotatorOptions() {
75
- return {
76
- filename: this.filename,
77
- frequency: this.frequency,
78
- verbose: this.verbose ?? false,
79
- date_format: this.dateFormat,
80
- size: this.size,
81
- max_logs: this.maxLogs?.toString(),
82
- audit_file: this.auditFile || void 0,
83
- end_stream: true,
84
- extension: this.extension,
85
- create_symlink: this.createSymlink,
86
- symlink_name: this.symlinkName,
87
- utc: this.utc,
88
- audit_hash_type: this.auditHashType,
89
- file_options: {
90
- flags: "a",
91
- encoding: "utf8",
92
- mode: this.fileMode ?? 416,
93
- ...this.fileOptions
94
- }
95
- };
96
- }
97
- /**
98
- * Creates a new LogFileRotationTransport instance.
99
- * @param params - Configuration options for the transport
100
- * @throws {Error} If the filename is already in use by another transport instance
101
- */
102
- constructor(params) {
103
- super(params);
104
- if (_LogFileRotationTransport.activeFilenames.has(params.filename)) {
105
- throw new Error(
106
- `LogFileRotationTransport: Filename "${params.filename}" is already in use by another instance. To use the same file for multiple loggers, share the same transport instance between them.`
107
- );
108
- }
109
- this.filename = params.filename;
110
- _LogFileRotationTransport.activeFilenames.add(this.filename);
111
- this.fieldNames = {
112
- level: params.fieldNames?.level ?? "level",
113
- message: params.fieldNames?.message ?? "message",
114
- timestamp: params.fieldNames?.timestamp ?? "timestamp"
115
- };
116
- this.delimiter = params.delimiter ?? "\n";
117
- this.timestampFn = params.timestampFn ?? (() => (/* @__PURE__ */ new Date()).toISOString());
118
- this.levelMap = params.levelMap ?? {};
119
- this.compressOnRotate = params.compressOnRotate ?? false;
120
- this.isCompressing = false;
121
- this.batchEnabled = !!params.batch;
122
- this.batchSize = params.batch?.size ?? 1e3;
123
- this.batchTimeout = params.batch?.timeout ?? 5e3;
124
- this.batchQueue = [];
125
- this.batchTimer = null;
126
- this.isDisposing = false;
127
- this.callbacks = params.callbacks;
128
- this.frequency = params.frequency;
129
- this.verbose = params.verbose;
130
- this.dateFormat = params.dateFormat;
131
- this.size = params.size;
132
- this.maxLogs = params.maxLogs;
133
- this.auditFile = params.auditFile;
134
- this.extension = params.extension;
135
- this.createSymlink = params.createSymlink;
136
- this.symlinkName = params.symlinkName;
137
- this.utc = params.utc;
138
- this.auditHashType = params.auditHashType;
139
- this.fileOptions = params.fileOptions;
140
- this.fileMode = params.fileMode;
141
- this.staticData = params.staticData;
142
- if (this.batchEnabled) {
143
- process.on("beforeExit", () => {
144
- if (!this.isDisposing) {
145
- this.flush();
146
- }
147
- });
148
- const handleSignal = (signal) => {
149
- if (!this.isDisposing) {
150
- this.flushSync();
151
- _LogFileRotationTransport.activeFilenames.delete(this.filename);
152
- process.exit(signal === "SIGINT" ? 130 : 143);
153
- }
154
- };
155
- process.on("SIGINT", () => handleSignal("SIGINT"));
156
- process.on("SIGTERM", () => handleSignal("SIGTERM"));
157
- }
158
- if (!this.batchEnabled) {
159
- this.initStream(this.getRotatorOptions());
160
- }
161
- }
162
- /**
163
- * Initializes the write stream and sets up event listeners.
164
- * This is called either immediately if batching is disabled,
165
- * or lazily when the first batch needs to be written if batching is enabled.
166
- * @param options - Options for the file stream rotator
167
- * @private
168
- */
169
- initStream(options) {
170
- this.stream = FileStreamRotator.getStream(options);
171
- if (this.callbacks) {
172
- const { onRotate, onNew, onOpen, onClose, onError, onFinish, onLogRemoved } = this.callbacks;
173
- if (this.compressOnRotate) {
174
- this.stream.on("rotate", async (oldFile, newFile) => {
175
- try {
176
- this.isCompressing = true;
177
- const compressedPath = await this.compressFile(oldFile);
178
- await unlink(oldFile);
179
- onRotate?.(compressedPath, newFile);
180
- } catch (error) {
181
- this.callbacks?.onError?.(error);
182
- } finally {
183
- this.isCompressing = false;
184
- }
185
- });
186
- } else if (onRotate) {
187
- this.stream.on("rotate", onRotate);
188
- }
189
- if (onNew) {
190
- this.stream.on("new", onNew);
191
- }
192
- if (onOpen) {
193
- this.stream.on("open", onOpen);
194
- }
195
- if (onClose) {
196
- this.stream.on("close", onClose);
197
- }
198
- if (onError) {
199
- this.stream.on("error", onError);
200
- }
201
- if (onFinish) {
202
- this.stream.on("finish", onFinish);
203
- }
204
- if (onLogRemoved) {
205
- this.stream.on("logRemoved", onLogRemoved);
206
- }
207
- }
208
- }
209
- /**
210
- * Generates a unique path for a compressed log file.
211
- * If a file with .gz extension already exists, appends timestamp and counter.
212
- * @param filePath - The original log file path
213
- * @returns The unique path for the compressed file
214
- * @private
215
- */
216
- async getUniqueCompressedFilePath(filePath) {
217
- let finalPath = `${filePath}.gz`;
218
- let counter = 0;
219
- try {
220
- while (true) {
221
- try {
222
- await access(finalPath);
223
- counter++;
224
- finalPath = `${filePath}.${Date.now()}.${counter}.gz`;
225
- } catch {
226
- break;
227
- }
228
- }
229
- } catch (_error) {
230
- finalPath = `${filePath}.${Date.now()}.gz`;
231
- }
232
- return finalPath;
233
- }
234
- /**
235
- * Compresses a log file using gzip.
236
- * @param filePath - Path to the file to compress
237
- * @returns Path to the compressed file
238
- * @private
239
- */
240
- async compressFile(filePath) {
241
- const gzPath = await this.getUniqueCompressedFilePath(filePath);
242
- const gzip = createGzip();
243
- const source = createReadStream(filePath);
244
- const destination = createWriteStream(gzPath);
245
- await pipeline(source, gzip, destination);
246
- return gzPath;
247
- }
248
- /**
249
- * Flushes queued log entries to disk asynchronously.
250
- * This is used for normal batch processing operations.
251
- * @private
252
- */
253
- flush() {
254
- if (!this.batchEnabled || this.batchQueue.length === 0) {
255
- return;
256
- }
257
- if (this.batchTimer) {
258
- clearTimeout(this.batchTimer);
259
- this.batchTimer = null;
260
- }
261
- if (!this.stream) {
262
- this.initStream(this.getRotatorOptions());
263
- }
264
- const batchContent = this.batchQueue.join("");
265
- this.stream.write(batchContent);
266
- this.batchQueue = [];
267
- }
268
- /**
269
- * Synchronously flush logs to disk.
270
- * This is used during process termination (SIGINT/SIGTERM) to ensure logs are written
271
- * before the process exits. This method uses synchronous file I/O to guarantee that
272
- * logs are written even during abrupt process termination.
273
- * @private
274
- */
275
- flushSync() {
276
- if (!this.batchEnabled || this.batchQueue.length === 0) {
277
- return;
278
- }
279
- if (this.batchTimer) {
280
- clearTimeout(this.batchTimer);
281
- this.batchTimer = null;
282
- }
283
- if (!this.stream) {
284
- this.initStream(this.getRotatorOptions());
285
- }
286
- const batchContent = this.batchQueue.join("");
287
- const rotator = this.stream;
288
- if (rotator.currentFile) {
289
- writeFileSync(rotator.currentFile, batchContent, { flag: "a" });
290
- }
291
- this.batchQueue = [];
292
- }
293
- /**
294
- * Schedules a batch flush operation.
295
- * This creates a timer that will flush the batch after the configured timeout.
296
- * The timer is unref'd to prevent keeping the process alive.
297
- * @private
298
- */
299
- scheduleBatchFlush() {
300
- if (!this.batchTimer && !this.isDisposing) {
301
- this.batchTimer = setTimeout(() => {
302
- this.flush();
303
- }, this.batchTimeout);
304
- if (this.batchTimer.unref) {
305
- this.batchTimer.unref();
306
- }
307
- }
308
- }
309
- /**
310
- * Processes and writes a log entry.
311
- * If batching is enabled, the entry is queued and written based on batch settings.
312
- * If batching is disabled, the entry is written immediately.
313
- * @param params - The log entry parameters
314
- * @returns The original messages array
315
- */
316
- shipToLogger({ logLevel, messages, data, hasData }) {
317
- const logEntry = {
318
- [this.fieldNames.level]: this.levelMap[logLevel] ?? logLevel,
319
- [this.fieldNames.message]: messages.join(" ") || "",
320
- [this.fieldNames.timestamp]: this.timestampFn(),
321
- ...this.staticData ? typeof this.staticData === "function" ? this.staticData() : this.staticData : {},
322
- ...hasData ? data : {}
323
- };
324
- const logString = `${JSON.stringify(logEntry)}${this.delimiter}`;
325
- if (this.batchEnabled) {
326
- this.batchQueue.push(logString);
327
- if (this.batchQueue.length >= this.batchSize) {
328
- this.flush();
329
- } else {
330
- this.scheduleBatchFlush();
331
- }
332
- } else {
333
- this.stream.write(logString);
334
- }
335
- return messages;
336
- }
337
- /**
338
- * Disposes of the transport, cleaning up resources and flushing any remaining logs.
339
- * This method:
340
- * 1. Prevents new batch flushes from being scheduled
341
- * 2. Cancels any pending batch flush
342
- * 3. Flushes any remaining logs
343
- * 4. Waits for any in-progress compression to complete
344
- * 5. Closes the write stream
345
- * 6. Removes the filename from the registry
346
- */
347
- [Symbol.dispose]() {
348
- if (this.stream || this.batchEnabled) {
349
- this.isDisposing = true;
350
- if (this.batchTimer) {
351
- clearTimeout(this.batchTimer);
352
- this.batchTimer = null;
353
- }
354
- if (this.batchEnabled) {
355
- this.flush();
356
- }
357
- const checkAndEnd = () => {
358
- if (!this.isCompressing) {
359
- if (this.stream) {
360
- this.stream.end();
361
- }
362
- _LogFileRotationTransport.activeFilenames.delete(this.filename);
363
- } else {
364
- setTimeout(checkAndEnd, 100);
365
- }
366
- };
367
- checkAndEnd();
368
- }
369
- }
370
- };
371
- export {
372
- LogFileRotationTransport
7
+
8
+ //#region src/LogFileRotationTransport.ts
9
+ /**
10
+ * A transport that writes logs to rotating files with support for time-based and size-based rotation.
11
+ * Features include:
12
+ * - Automatic log file rotation based on time (hourly, daily) or size
13
+ * - Support for date patterns in filenames using numerical values (YYYY, MM, DD, etc.)
14
+ * - Size-based rotation with support for KB, MB, and GB units
15
+ * - Compression of rotated log files using gzip
16
+ * - Maximum file count or age-based retention
17
+ * - Automatic cleanup of old log files
18
+ * - Batch processing of logs for improved performance
19
+ * - Safe handling of process termination signals
20
+ *
21
+ * Each instance must have a unique filename to prevent race conditions.
22
+ * If you need multiple loggers to write to the same file, share the same transport instance between them.
23
+ */
24
+ var LogFileRotationTransport = class LogFileRotationTransport extends LoggerlessTransport {
25
+ /** Registry of active filenames to prevent multiple transports writing to the same file */
26
+ static activeFilenames = /* @__PURE__ */ new Set();
27
+ /** The current write stream for the log file */
28
+ stream;
29
+ /** Custom field names for log entries */
30
+ fieldNames;
31
+ /** Delimiter between log entries */
32
+ delimiter;
33
+ /** Function to generate timestamps for log entries */
34
+ timestampFn;
35
+ /** Custom mapping for log levels */
36
+ levelMap;
37
+ /** Whether to compress rotated files */
38
+ compressOnRotate;
39
+ /** Whether a file is currently being compressed */
40
+ isCompressing;
41
+ /** The base filename pattern for log files */
42
+ filename;
43
+ /** Static data to be included in every log entry */
44
+ staticData;
45
+ /** Whether batch processing is enabled */
46
+ batchEnabled;
47
+ /** Maximum number of log entries to queue before writing */
48
+ batchSize;
49
+ /** Maximum time in milliseconds to wait before writing queued logs */
50
+ batchTimeout;
51
+ /** Queue of log entries waiting to be written */
52
+ batchQueue;
53
+ /** Timer for batch flush timeout */
54
+ batchTimer;
55
+ /** Whether the transport is being disposed */
56
+ isDisposing;
57
+ /** Event callbacks for various file stream events */
58
+ callbacks;
59
+ /** Frequency of rotation (daily, hourly, etc.) */
60
+ frequency;
61
+ /** Whether to enable verbose mode */
62
+ verbose;
63
+ /** Date format for filename patterns */
64
+ dateFormat;
65
+ /** Size threshold for rotation */
66
+ size;
67
+ /** Maximum number of log files to keep */
68
+ maxLogs;
69
+ /** Path to the audit file */
70
+ auditFile;
71
+ /** File extension for log files */
72
+ extension;
73
+ /** Whether to create a symlink to current log */
74
+ createSymlink;
75
+ /** Name of the symlink file */
76
+ symlinkName;
77
+ /** Whether to use UTC time in filenames */
78
+ utc;
79
+ /** Hash algorithm for audit file */
80
+ auditHashType;
81
+ /** Options for file streams */
82
+ fileOptions;
83
+ /** File mode to be used when creating log files */
84
+ fileMode;
85
+ /**
86
+ * Generates the options for FileStreamRotator consistently across the transport
87
+ * @returns FileStreamRotatorOptions object
88
+ * @private
89
+ */
90
+ getRotatorOptions() {
91
+ return {
92
+ filename: this.filename,
93
+ frequency: this.frequency,
94
+ verbose: this.verbose ?? false,
95
+ date_format: this.dateFormat,
96
+ size: this.size,
97
+ max_logs: this.maxLogs?.toString(),
98
+ audit_file: this.auditFile || void 0,
99
+ end_stream: true,
100
+ extension: this.extension,
101
+ create_symlink: this.createSymlink,
102
+ symlink_name: this.symlinkName,
103
+ utc: this.utc,
104
+ audit_hash_type: this.auditHashType,
105
+ file_options: {
106
+ flags: "a",
107
+ encoding: "utf8",
108
+ mode: this.fileMode ?? 416,
109
+ ...this.fileOptions
110
+ }
111
+ };
112
+ }
113
+ /**
114
+ * Creates a new LogFileRotationTransport instance.
115
+ * @param params - Configuration options for the transport
116
+ * @throws {Error} If the filename is already in use by another transport instance
117
+ */
118
+ constructor(params) {
119
+ super(params);
120
+ if (LogFileRotationTransport.activeFilenames.has(params.filename)) throw new Error(`LogFileRotationTransport: Filename "${params.filename}" is already in use by another instance. To use the same file for multiple loggers, share the same transport instance between them.`);
121
+ this.filename = params.filename;
122
+ LogFileRotationTransport.activeFilenames.add(this.filename);
123
+ this.fieldNames = {
124
+ level: params.fieldNames?.level ?? "level",
125
+ message: params.fieldNames?.message ?? "message",
126
+ timestamp: params.fieldNames?.timestamp ?? "timestamp"
127
+ };
128
+ this.delimiter = params.delimiter ?? "\n";
129
+ this.timestampFn = params.timestampFn ?? (() => (/* @__PURE__ */ new Date()).toISOString());
130
+ this.levelMap = params.levelMap ?? {};
131
+ this.compressOnRotate = params.compressOnRotate ?? false;
132
+ this.isCompressing = false;
133
+ this.batchEnabled = !!params.batch;
134
+ this.batchSize = params.batch?.size ?? 1e3;
135
+ this.batchTimeout = params.batch?.timeout ?? 5e3;
136
+ this.batchQueue = [];
137
+ this.batchTimer = null;
138
+ this.isDisposing = false;
139
+ this.callbacks = params.callbacks;
140
+ this.frequency = params.frequency;
141
+ this.verbose = params.verbose;
142
+ this.dateFormat = params.dateFormat;
143
+ this.size = params.size;
144
+ this.maxLogs = params.maxLogs;
145
+ this.auditFile = params.auditFile;
146
+ this.extension = params.extension;
147
+ this.createSymlink = params.createSymlink;
148
+ this.symlinkName = params.symlinkName;
149
+ this.utc = params.utc;
150
+ this.auditHashType = params.auditHashType;
151
+ this.fileOptions = params.fileOptions;
152
+ this.fileMode = params.fileMode;
153
+ this.staticData = params.staticData;
154
+ if (this.batchEnabled) {
155
+ process.on("beforeExit", () => {
156
+ if (!this.isDisposing) this.flush();
157
+ });
158
+ const handleSignal = (signal) => {
159
+ if (!this.isDisposing) {
160
+ this.flushSync();
161
+ LogFileRotationTransport.activeFilenames.delete(this.filename);
162
+ process.exit(signal === "SIGINT" ? 130 : 143);
163
+ }
164
+ };
165
+ process.on("SIGINT", () => handleSignal("SIGINT"));
166
+ process.on("SIGTERM", () => handleSignal("SIGTERM"));
167
+ }
168
+ if (!this.batchEnabled) this.initStream(this.getRotatorOptions());
169
+ }
170
+ /**
171
+ * Initializes the write stream and sets up event listeners.
172
+ * This is called either immediately if batching is disabled,
173
+ * or lazily when the first batch needs to be written if batching is enabled.
174
+ * @param options - Options for the file stream rotator
175
+ * @private
176
+ */
177
+ initStream(options) {
178
+ this.stream = FileStreamRotator.getStream(options);
179
+ if (this.callbacks) {
180
+ const { onRotate, onNew, onOpen, onClose, onError, onFinish, onLogRemoved } = this.callbacks;
181
+ if (this.compressOnRotate) this.stream.on("rotate", async (oldFile, newFile) => {
182
+ try {
183
+ this.isCompressing = true;
184
+ const compressedPath = await this.compressFile(oldFile);
185
+ await unlink(oldFile);
186
+ onRotate?.(compressedPath, newFile);
187
+ } catch (error) {
188
+ this.callbacks?.onError?.(error);
189
+ } finally {
190
+ this.isCompressing = false;
191
+ }
192
+ });
193
+ else if (onRotate) this.stream.on("rotate", onRotate);
194
+ if (onNew) this.stream.on("new", onNew);
195
+ if (onOpen) this.stream.on("open", onOpen);
196
+ if (onClose) this.stream.on("close", onClose);
197
+ if (onError) this.stream.on("error", onError);
198
+ if (onFinish) this.stream.on("finish", onFinish);
199
+ if (onLogRemoved) this.stream.on("logRemoved", onLogRemoved);
200
+ }
201
+ }
202
+ /**
203
+ * Generates a unique path for a compressed log file.
204
+ * If a file with .gz extension already exists, appends timestamp and counter.
205
+ * @param filePath - The original log file path
206
+ * @returns The unique path for the compressed file
207
+ * @private
208
+ */
209
+ async getUniqueCompressedFilePath(filePath) {
210
+ let finalPath = `${filePath}.gz`;
211
+ let counter = 0;
212
+ try {
213
+ while (true) try {
214
+ await access(finalPath);
215
+ counter++;
216
+ finalPath = `${filePath}.${Date.now()}.${counter}.gz`;
217
+ } catch {
218
+ break;
219
+ }
220
+ } catch (_error) {
221
+ finalPath = `${filePath}.${Date.now()}.gz`;
222
+ }
223
+ return finalPath;
224
+ }
225
+ /**
226
+ * Compresses a log file using gzip.
227
+ * @param filePath - Path to the file to compress
228
+ * @returns Path to the compressed file
229
+ * @private
230
+ */
231
+ async compressFile(filePath) {
232
+ const gzPath = await this.getUniqueCompressedFilePath(filePath);
233
+ const gzip = createGzip();
234
+ await pipeline(createReadStream(filePath), gzip, createWriteStream(gzPath));
235
+ return gzPath;
236
+ }
237
+ /**
238
+ * Flushes queued log entries to disk asynchronously.
239
+ * This is used for normal batch processing operations.
240
+ * @private
241
+ */
242
+ flush() {
243
+ if (!this.batchEnabled || this.batchQueue.length === 0) return;
244
+ if (this.batchTimer) {
245
+ clearTimeout(this.batchTimer);
246
+ this.batchTimer = null;
247
+ }
248
+ if (!this.stream) this.initStream(this.getRotatorOptions());
249
+ const batchContent = this.batchQueue.join("");
250
+ this.stream.write(batchContent);
251
+ this.batchQueue = [];
252
+ }
253
+ /**
254
+ * Synchronously flush logs to disk.
255
+ * This is used during process termination (SIGINT/SIGTERM) to ensure logs are written
256
+ * before the process exits. This method uses synchronous file I/O to guarantee that
257
+ * logs are written even during abrupt process termination.
258
+ * @private
259
+ */
260
+ flushSync() {
261
+ if (!this.batchEnabled || this.batchQueue.length === 0) return;
262
+ if (this.batchTimer) {
263
+ clearTimeout(this.batchTimer);
264
+ this.batchTimer = null;
265
+ }
266
+ if (!this.stream) this.initStream(this.getRotatorOptions());
267
+ const batchContent = this.batchQueue.join("");
268
+ const rotator = this.stream;
269
+ if (rotator.currentFile) writeFileSync(rotator.currentFile, batchContent, { flag: "a" });
270
+ this.batchQueue = [];
271
+ }
272
+ /**
273
+ * Schedules a batch flush operation.
274
+ * This creates a timer that will flush the batch after the configured timeout.
275
+ * The timer is unref'd to prevent keeping the process alive.
276
+ * @private
277
+ */
278
+ scheduleBatchFlush() {
279
+ if (!this.batchTimer && !this.isDisposing) {
280
+ this.batchTimer = setTimeout(() => {
281
+ this.flush();
282
+ }, this.batchTimeout);
283
+ if (this.batchTimer.unref) this.batchTimer.unref();
284
+ }
285
+ }
286
+ /**
287
+ * Processes and writes a log entry.
288
+ * If batching is enabled, the entry is queued and written based on batch settings.
289
+ * If batching is disabled, the entry is written immediately.
290
+ * @param params - The log entry parameters
291
+ * @returns The original messages array
292
+ */
293
+ shipToLogger({ logLevel, messages, data, hasData }) {
294
+ const logEntry = {
295
+ [this.fieldNames.level]: this.levelMap[logLevel] ?? logLevel,
296
+ [this.fieldNames.message]: messages.join(" ") || "",
297
+ [this.fieldNames.timestamp]: this.timestampFn(),
298
+ ...this.staticData ? typeof this.staticData === "function" ? this.staticData() : this.staticData : {},
299
+ ...hasData ? data : {}
300
+ };
301
+ const logString = `${JSON.stringify(logEntry)}${this.delimiter}`;
302
+ if (this.batchEnabled) {
303
+ this.batchQueue.push(logString);
304
+ if (this.batchQueue.length >= this.batchSize) this.flush();
305
+ else this.scheduleBatchFlush();
306
+ } else this.stream.write(logString);
307
+ return messages;
308
+ }
309
+ /**
310
+ * Disposes of the transport, cleaning up resources and flushing any remaining logs.
311
+ * This method:
312
+ * 1. Prevents new batch flushes from being scheduled
313
+ * 2. Cancels any pending batch flush
314
+ * 3. Flushes any remaining logs
315
+ * 4. Waits for any in-progress compression to complete
316
+ * 5. Closes the write stream
317
+ * 6. Removes the filename from the registry
318
+ */
319
+ [Symbol.dispose]() {
320
+ if (this.stream || this.batchEnabled) {
321
+ this.isDisposing = true;
322
+ if (this.batchTimer) {
323
+ clearTimeout(this.batchTimer);
324
+ this.batchTimer = null;
325
+ }
326
+ if (this.batchEnabled) this.flush();
327
+ const checkAndEnd = () => {
328
+ if (!this.isCompressing) {
329
+ if (this.stream) this.stream.end();
330
+ LogFileRotationTransport.activeFilenames.delete(this.filename);
331
+ } else setTimeout(checkAndEnd, 100);
332
+ };
333
+ checkAndEnd();
334
+ }
335
+ }
373
336
  };
337
+
338
+ //#endregion
339
+ export { LogFileRotationTransport };
374
340
  //# sourceMappingURL=index.js.map