@loglayer/transport-log-file-rotation 1.0.0

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.
@@ -0,0 +1,393 @@
1
+ import { LoggerlessTransportConfig, LoggerlessTransport, LogLayerTransportParams } from '@loglayer/transport';
2
+
3
+ interface LogFileRotationCallbacks {
4
+ /**
5
+ * Called when a log file is rotated
6
+ * @param oldFile - The path to the old log file
7
+ * @param newFile - The path to the new log file
8
+ */
9
+ onRotate?: (oldFile: string, newFile: string) => void;
10
+ /**
11
+ * Called when a new log file is created
12
+ * @param newFile - The path to the new log file
13
+ */
14
+ onNew?: (newFile: string) => void;
15
+ /**
16
+ * Called when a log file is opened
17
+ */
18
+ onOpen?: () => void;
19
+ /**
20
+ * Called when a log file is closed
21
+ */
22
+ onClose?: () => void;
23
+ /**
24
+ * Called when an error occurs
25
+ * @param error - The error that occurred
26
+ */
27
+ onError?: (error: Error) => void;
28
+ /**
29
+ * Called when the stream is finished
30
+ */
31
+ onFinish?: () => void;
32
+ /**
33
+ * Called when a log file is removed due to retention policy
34
+ * @param info - Information about the removed log file
35
+ */
36
+ onLogRemoved?: (info: {
37
+ date: number;
38
+ name: string;
39
+ hash: string;
40
+ }) => void;
41
+ }
42
+ interface LogFileRotationFieldNames {
43
+ /**
44
+ * Field name for the log level
45
+ * @default "level"
46
+ */
47
+ level?: string;
48
+ /**
49
+ * Field name for the log message
50
+ * @default "message"
51
+ */
52
+ message?: string;
53
+ /**
54
+ * Field name for the timestamp
55
+ * @default "timestamp"
56
+ */
57
+ timestamp?: string;
58
+ }
59
+ interface LogFileRotationLevelMap {
60
+ /**
61
+ * Mapping for the 'fatal' log level
62
+ * @example 60 or "FATAL"
63
+ */
64
+ fatal?: string | number;
65
+ /**
66
+ * Mapping for the 'error' log level
67
+ * @example 50 or "ERROR"
68
+ */
69
+ error?: string | number;
70
+ /**
71
+ * Mapping for the 'warn' log level
72
+ * @example 40 or "WARN"
73
+ */
74
+ warn?: string | number;
75
+ /**
76
+ * Mapping for the 'info' log level
77
+ * @example 30 or "INFO"
78
+ */
79
+ info?: string | number;
80
+ /**
81
+ * Mapping for the 'debug' log level
82
+ * @example 20 or "DEBUG"
83
+ */
84
+ debug?: string | number;
85
+ /**
86
+ * Mapping for the 'trace' log level
87
+ * @example 10 or "TRACE"
88
+ */
89
+ trace?: string | number;
90
+ }
91
+ interface LogFileRotationBatchConfig {
92
+ /**
93
+ * Maximum number of log entries to queue before writing.
94
+ * Default: 1000
95
+ */
96
+ size?: number;
97
+ /**
98
+ * Maximum time in milliseconds to wait before writing queued logs.
99
+ * Default: 5000 (5 seconds)
100
+ */
101
+ timeout?: number;
102
+ }
103
+ interface LogFileRotationTransportConfig extends LoggerlessTransportConfig {
104
+ /**
105
+ * The filename pattern to use for the log files.
106
+ * Supports date format using numerical values.
107
+ * Example: "./logs/application-%DATE%.log"
108
+ */
109
+ filename: string;
110
+ /**
111
+ * The frequency of rotation. Can be:
112
+ * - 'daily' for daily rotation
113
+ * - 'date' for rotation on date format change
114
+ * - '[1-30]m' for rotation every X minutes
115
+ * - '[1-12]h' for rotation every X hours
116
+ */
117
+ frequency?: string;
118
+ /**
119
+ * The date format to use in the filename.
120
+ * Uses single characters for each date component:
121
+ * - 'Y' for full year
122
+ * - 'M' for month
123
+ * - 'D' for day
124
+ * - 'H' for hour
125
+ * - 'm' for minutes
126
+ * - 's' for seconds
127
+ *
128
+ * Common patterns:
129
+ * - For daily rotation: use "YMD" (creates files like app-20240117.log)
130
+ * - For hourly/minute rotation: use "YMDHm" (creates files like app-202401171430.log)
131
+ *
132
+ * @default "YMD"
133
+ */
134
+ dateFormat?: string;
135
+ /**
136
+ * The size at which to rotate.
137
+ * Examples: "10M", "100K", "100B"
138
+ * If frequency is specified, this will be ignored.
139
+ */
140
+ size?: string;
141
+ /**
142
+ * Maximum number of logs to keep.
143
+ * Can be a number of files or days (e.g., "10d" for 10 days)
144
+ */
145
+ maxLogs?: string | number;
146
+ /**
147
+ * Location to store the log audit file.
148
+ * If not set, it will be stored in the root of the application.
149
+ */
150
+ auditFile?: string;
151
+ /**
152
+ * File extension to be appended to the filename.
153
+ * Useful when using size restrictions as the rotation adds a count at the end.
154
+ */
155
+ extension?: string;
156
+ /**
157
+ * Create a tailable symlink to the current active log file.
158
+ * Default: false
159
+ */
160
+ createSymlink?: boolean;
161
+ /**
162
+ * Name to use when creating the symbolic link.
163
+ * Default: 'current.log'
164
+ */
165
+ symlinkName?: string;
166
+ /**
167
+ * Use UTC time for date in filename.
168
+ * Default: false
169
+ */
170
+ utc?: boolean;
171
+ /**
172
+ * Use specified hashing algorithm for audit.
173
+ * Default: 'md5'
174
+ * Use 'sha256' for FIPS compliance.
175
+ */
176
+ auditHashType?: "md5" | "sha256";
177
+ /**
178
+ * File mode to be used when creating log files.
179
+ * Default: 0o640 (user read/write, group read, others none)
180
+ */
181
+ fileMode?: number;
182
+ /**
183
+ * Options passed to the file stream.
184
+ * See: https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options
185
+ */
186
+ fileOptions?: {
187
+ flags?: string;
188
+ encoding?: string;
189
+ mode?: number;
190
+ };
191
+ /**
192
+ * Event callbacks for various file stream events
193
+ */
194
+ callbacks?: LogFileRotationCallbacks;
195
+ /**
196
+ * Custom field names for the log entry JSON
197
+ * Default: { level: "level", message: "message", data: "data", timestamp: "timestamp" }
198
+ */
199
+ fieldNames?: LogFileRotationFieldNames;
200
+ /**
201
+ * Delimiter between log entries.
202
+ * Default: "\n"
203
+ */
204
+ delimiter?: string;
205
+ /**
206
+ * Custom function to generate timestamps for log entries.
207
+ * Can return either a string (e.g., ISO string) or a number (e.g., Unix timestamp)
208
+ * If not provided, defaults to new Date().toISOString()
209
+ */
210
+ timestampFn?: () => string | number;
211
+ /**
212
+ * Custom mapping for log levels.
213
+ * Each log level can be mapped to either a string or number.
214
+ * Example: { error: 50, warn: 40, info: 30, debug: 20, trace: 10, fatal: 60 }
215
+ * Example: { error: "ERROR", warn: "WARN", info: "INFO", debug: "DEBUG", trace: "TRACE", fatal: "FATAL" }
216
+ */
217
+ levelMap?: LogFileRotationLevelMap;
218
+ /**
219
+ * Whether to compress rotated log files using gzip.
220
+ * When enabled, rotated files will be compressed with .gz extension.
221
+ * Default: false
222
+ */
223
+ compressOnRotate?: boolean;
224
+ /**
225
+ * Whether to enable verbose mode in the underlying file-stream-rotator.
226
+ * When enabled, the rotator will log detailed information about its operations.
227
+ * Default: false
228
+ */
229
+ verbose?: boolean;
230
+ /**
231
+ * Batch processing configuration.
232
+ * If defined, batch processing will be enabled.
233
+ * When batching is enabled, logs are queued in memory and written to disk in batches.
234
+ * Queued logs are automatically flushed in the following situations:
235
+ * - When the batch size is reached
236
+ * - When the batch timeout is reached
237
+ * - When the transport is disposed
238
+ * - When the process exits (including SIGINT and SIGTERM signals)
239
+ */
240
+ batch?: LogFileRotationBatchConfig;
241
+ }
242
+ /**
243
+ * A transport that writes logs to rotating files with support for time-based and size-based rotation.
244
+ * Features include:
245
+ * - Automatic log file rotation based on time (hourly, daily) or size
246
+ * - Support for date patterns in filenames using numerical values (YYYY, MM, DD, etc.)
247
+ * - Size-based rotation with support for KB, MB, and GB units
248
+ * - Compression of rotated log files using gzip
249
+ * - Maximum file count or age-based retention
250
+ * - Automatic cleanup of old log files
251
+ * - Batch processing of logs for improved performance
252
+ * - Safe handling of process termination signals
253
+ *
254
+ * Each instance must have a unique filename to prevent race conditions.
255
+ * If you need multiple loggers to write to the same file, share the same transport instance between them.
256
+ */
257
+ declare class LogFileRotationTransport extends LoggerlessTransport implements Disposable {
258
+ /** Registry of active filenames to prevent multiple transports writing to the same file */
259
+ private static activeFilenames;
260
+ /** The current write stream for the log file */
261
+ private stream;
262
+ /** Custom field names for log entries */
263
+ private fieldNames;
264
+ /** Delimiter between log entries */
265
+ private delimiter;
266
+ /** Function to generate timestamps for log entries */
267
+ private timestampFn;
268
+ /** Custom mapping for log levels */
269
+ private levelMap;
270
+ /** Whether to compress rotated files */
271
+ private compressOnRotate;
272
+ /** Whether a file is currently being compressed */
273
+ private isCompressing;
274
+ /** The base filename pattern for log files */
275
+ private filename;
276
+ /** Whether batch processing is enabled */
277
+ private batchEnabled;
278
+ /** Maximum number of log entries to queue before writing */
279
+ private batchSize;
280
+ /** Maximum time in milliseconds to wait before writing queued logs */
281
+ private batchTimeout;
282
+ /** Queue of log entries waiting to be written */
283
+ private batchQueue;
284
+ /** Timer for batch flush timeout */
285
+ private batchTimer;
286
+ /** Whether the transport is being disposed */
287
+ private isDisposing;
288
+ /** Event callbacks for various file stream events */
289
+ private callbacks?;
290
+ /** Frequency of rotation (daily, hourly, etc.) */
291
+ private frequency?;
292
+ /** Whether to enable verbose mode */
293
+ private verbose?;
294
+ /** Date format for filename patterns */
295
+ private dateFormat?;
296
+ /** Size threshold for rotation */
297
+ private size?;
298
+ /** Maximum number of log files to keep */
299
+ private maxLogs?;
300
+ /** Path to the audit file */
301
+ private auditFile?;
302
+ /** File extension for log files */
303
+ private extension?;
304
+ /** Whether to create a symlink to current log */
305
+ private createSymlink?;
306
+ /** Name of the symlink file */
307
+ private symlinkName?;
308
+ /** Whether to use UTC time in filenames */
309
+ private utc?;
310
+ /** Hash algorithm for audit file */
311
+ private auditHashType?;
312
+ /** Options for file streams */
313
+ private fileOptions?;
314
+ /** File mode to be used when creating log files */
315
+ private fileMode?;
316
+ /**
317
+ * Generates the options for FileStreamRotator consistently across the transport
318
+ * @returns FileStreamRotatorOptions object
319
+ * @private
320
+ */
321
+ private getRotatorOptions;
322
+ /**
323
+ * Creates a new LogFileRotationTransport instance.
324
+ * @param params - Configuration options for the transport
325
+ * @throws {Error} If the filename is already in use by another transport instance
326
+ */
327
+ constructor(params: LogFileRotationTransportConfig);
328
+ /**
329
+ * Initializes the write stream and sets up event listeners.
330
+ * This is called either immediately if batching is disabled,
331
+ * or lazily when the first batch needs to be written if batching is enabled.
332
+ * @param options - Options for the file stream rotator
333
+ * @private
334
+ */
335
+ private initStream;
336
+ /**
337
+ * Generates a unique path for a compressed log file.
338
+ * If a file with .gz extension already exists, appends timestamp and counter.
339
+ * @param filePath - The original log file path
340
+ * @returns The unique path for the compressed file
341
+ * @private
342
+ */
343
+ private getUniqueCompressedFilePath;
344
+ /**
345
+ * Compresses a log file using gzip.
346
+ * @param filePath - Path to the file to compress
347
+ * @returns Path to the compressed file
348
+ * @private
349
+ */
350
+ private compressFile;
351
+ /**
352
+ * Flushes queued log entries to disk asynchronously.
353
+ * This is used for normal batch processing operations.
354
+ * @private
355
+ */
356
+ private flush;
357
+ /**
358
+ * Synchronously flush logs to disk.
359
+ * This is used during process termination (SIGINT/SIGTERM) to ensure logs are written
360
+ * before the process exits. This method uses synchronous file I/O to guarantee that
361
+ * logs are written even during abrupt process termination.
362
+ * @private
363
+ */
364
+ private flushSync;
365
+ /**
366
+ * Schedules a batch flush operation.
367
+ * This creates a timer that will flush the batch after the configured timeout.
368
+ * The timer is unref'd to prevent keeping the process alive.
369
+ * @private
370
+ */
371
+ private scheduleBatchFlush;
372
+ /**
373
+ * Processes and writes a log entry.
374
+ * If batching is enabled, the entry is queued and written based on batch settings.
375
+ * If batching is disabled, the entry is written immediately.
376
+ * @param params - The log entry parameters
377
+ * @returns The original messages array
378
+ */
379
+ shipToLogger({ logLevel, messages, data, hasData }: LogLayerTransportParams): any[];
380
+ /**
381
+ * Disposes of the transport, cleaning up resources and flushing any remaining logs.
382
+ * This method:
383
+ * 1. Prevents new batch flushes from being scheduled
384
+ * 2. Cancels any pending batch flush
385
+ * 3. Flushes any remaining logs
386
+ * 4. Waits for any in-progress compression to complete
387
+ * 5. Closes the write stream
388
+ * 6. Removes the filename from the registry
389
+ */
390
+ [Symbol.dispose](): void;
391
+ }
392
+
393
+ export { type LogFileRotationBatchConfig, type LogFileRotationCallbacks, type LogFileRotationFieldNames, type LogFileRotationLevelMap, LogFileRotationTransport, type LogFileRotationTransportConfig };