Creates a new AsyncFileTransport instance.
Configuration options
ProtectedclosingFlag to track if transport is currently closing.
Whether this transport is currently active and processing logs. Can be toggled at runtime to enable/disable specific transports.
Protected Optional ReadonlyexcludeTags that exclude logs from being processed.
Protected Optional ReadonlyfilterCustom filter function for advanced filtering.
Protected ReadonlyformatOutput format for this transport.
Protected Optional ReadonlyformatterCustom formatter function.
ProtectedinitializedFlag to track if transport has been initialized.
Protected ReadonlylevelMinimum log level for this transport.
Protected Optional ReadonlylevelsSpecific levels this transport handles (if specified).
ReadonlynameUnique identifier for this transport instance. Used for managing multiple transports and debugging.
Protected ReadonlyoptionsTransport configuration options.
Protected ReadonlysilentWhether to suppress errors from this transport.
ProtectedstatsStatistics tracking for this transport.
Protected Optional ReadonlytagsTags that must be present for logs to be processed.
Protected ReadonlytimeoutOperation timeout in milliseconds.
Disable the transport.
ProtecteddoProtectedClose the transport gracefully.
Performs a clean shutdown:
Resolves when fully closed
ProtecteddoProtectedInitialize the transport with sonic-boom.
Creates the sonic-boom instance and sets up event handlers for:
This method is called automatically by the Transport base class when the transport is first used or explicitly via init().
sonic-boom provides:
ProtecteddoProtectedLegacy async doLog for compatibility with Transport base class.
This method is not used when log() and logSync() are overridden, but is kept for compatibility with the Transport interface.
The log entry
Protected OptionaldoProtectedOptional method for transport-specific batch logging. Subclasses can implement this for efficient batch processing.
Array of log entries to process
Resolves when all logs have been processed
Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
to each.
Returns true if the event had listeners, false otherwise.
import EventEmitter from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
Enable the transport.
Flush any buffered data to disk.
Forces all pending log entries to be written immediately. This is useful for:
Resolves when all data is written
ProtectedformatProtectedFormat log entry for output.
Converts log entries to JSON string format for file storage. Optimized for minimal overhead with direct JSON serialization.
Supports both:
The log entry to format
JSON string representation
ProtectedformatProtectedFormat a log entry as plain text.
The log entry to format
Plain text formatted log entry
ProtectedgenerateProtectedGenerate a unique ID for tracking purposes.
A unique identifier
Get the transport name.
Get transport statistics including buffer status.
Provides detailed metrics for monitoring and debugging:
Statistics object with buffer info
Optionalcustom?: Record<string, unknown>Transport-specific metrics.
Total logs that failed to send.
OptionallastError?: { count: number; message: string; timestamp: Date }Last error that occurred.
OptionallastSuccess?: DateLast successful log timestamp.
Optionallogged?: numberAlias for succeeded count, provided for readability in some consumers/tests.
Optionalname?: stringOptional transport identifier for convenience in tests/metrics.
Total logs processed by this transport.
Optionalqueued?: numberCurrent number of logs in queue (if applicable).
Optionalsent?: numberAdditional alias for succeeded count expected by some tests/consumers.
Total logs successfully sent.
ProtectedhandleProtectedHandle errors according to the transport's configuration.
The error that occurred
Optionalentry: LogEntryThe log entry that caused the error (if applicable)
Check if the transport is currently enabled.
True if transport is enabled
Check if transport is healthy.
True if transport is healthy
ProtectedisProtectedCheck if a log level is enabled based on minimum level.
The level to check
True if the level is enabled
Async log method for compatibility with base Transport interface.
This method delegates to logSync() for performance, then returns an immediately resolved Promise for API compatibility. When called directly (not via TransportManager), this still provides async behavior but with some Promise overhead.
The log entry to process
Immediately resolved promise
Logs an entry truly asynchronously with backpressure handling.
The log entry
Resolves when written
Logs a batch of entries efficiently. This is the most performant way to write multiple entries.
Batch of log entries
Resolves when all written
Synchronous log method with application-level batching for maximum performance.
This method implements a two-level batching strategy:
Benefits of application-level batching:
How it works:
Performance improvements:
The log entry to process
Alias for emitter.removeListener().
Implement EventEmitter methods explicitly for ITransport interface.
Reopen the log file.
Useful for log rotation scenarios where you want to:
Note: This doesn't rename the file - you need to handle that externally.
Resolves when file is reopened
// Rotate logs daily
async function rotateLogs(transport: AsyncFileTransport) {
const oldPath = './logs/app.log';
const newPath = `./logs/app-${Date.now()}.log`;
// Flush pending writes
await transport.flush();
// Rename the current file
fs.renameSync(oldPath, newPath);
// Reopen to create new file
await transport.reopen();
}
Reset transport statistics.
Check if this transport should handle a given log entry.
The log entry to check
True if the entry should be logged by this transport
ProtectedshouldProtectedWhether this transport should rethrow errors encountered during log operations. Network-based transports typically want propagation so callers/tests can assert failures. Base transports default to swallowing errors after emitting events and updating stats.
Check if transport supports batching.
True if batching is supported
Protectedwith
High-performance asynchronous file transport using sonic-boom.
This transport provides enterprise-grade file logging with:
Technical Implementation:
Performance vs Previous Implementation:
AsyncFileTransport
Example: Basic Usage
Example: Advanced Configuration
Example: Log Rotation