@pawells/logger-file-transport
v3.0.0
Published
File transport for @pawells/logger — writes formatted log entries to disk with automatic size-based rotation
Downloads
195
Maintainers
Readme
@pawells/logger-file-transport
File transport for @pawells/logger — writes formatted log entries to disk with automatic size-based rotation and configurable archival.
Features
- Automatic rotation — Rotates log files when they exceed a configured size threshold
- Configurable archival — Retain multiple archive files with automatic cleanup of oldest entries
- Async I/O — Non-blocking file writes using Node.js
fs/promises - Custom formatting — Use JSON formatter (default) or supply a custom
LogFormatter - Directory creation — Automatically creates parent directories if they don't exist
- Graceful error handling — Handles file I/O errors without crashing the logging system
- ESM-only — Modern JavaScript modules, no CommonJS
Installation
npm install @pawells/logger @pawells/logger-file-transport
# or
yarn add @pawells/logger @pawells/logger-file-transportBoth packages are required: @pawells/logger-file-transport extends LogTransport from the core @pawells/logger library.
Requirements
- Node.js >= 22.0.0
@pawells/loggeras a peer dependency
Quick Start
import { Logger, LogManager } from '@pawells/logger';
import { FileTransport } from '@pawells/logger-file-transport';
// Set application-level context (optional)
LogManager.Context = 'my-app';
// Create a file transport
const transport = new FileTransport({
filePath: '/var/log/my-app.log',
rotation: {
enabled: true,
maxFileSize: 10_485_760, // 10 MB
maxArchives: 5,
},
});
// Create a logger and emit entries
const logger = new Logger('main');
logger.info('Application started', { version: '1.0.0' });
logger.warn('Feature disabled', { feature: 'auth' });
logger.error('Database connection failed', new Error('ECONNREFUSED'));API
FileTransport
A LogTransport subclass that writes formatted log entries to a file on disk with automatic size-based rotation.
Constructor
constructor(options: IFileTransportOptions, fsModule?: FsModuleType)Creates a new file transport and begins async initialization (directory creation, file opening).
Parameters:
options— Configuration object (seeIFileTransportOptionsbelow)fsModule— (Internal/Testing) Optionalfs/promisesmodule for dependency injection; defaults to Node.jsfs/promises
Throws:
Errorif directory creation fails or file cannot be opened (after initialization completes)
Example:
const transport = new FileTransport({
filePath: './logs/app.log',
formatter: new TextLogFormatter(),
filters: [LogLevelFilter(LogLevels.INFO)],
rotation: { enabled: true, maxFileSize: 5_242_880 }, // 5 MB
});IFileTransportOptions
Configuration object for FileTransport.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| filePath | string | required | Absolute or relative path to the log file. Parent directory is created automatically if it doesn't exist. |
| formatter | LogFormatter | JSONLogFormatter | Formatter to convert ILogEntry objects to strings. Defaults to JSONLogFormatter for structured log aggregation. |
| filters | ILogEntryPredicate[] | [] | Array of filter predicates to apply. Use LogLevelFilter(minLevel) for level-based filtering. |
| rotation | IFileRotationOptions | See below | File rotation configuration. Omit to use defaults (enabled with 10 MB threshold and 5 archives). |
IFileRotationOptions
Controls automatic file rotation when the log file exceeds a size threshold.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| enabled | boolean | true | Enable automatic rotation when file size exceeds maxFileSize. |
| maxFileSize | number | 10_485_760 | Maximum file size in bytes (10 MB) before rotation is triggered. |
| maxArchives | number | 5 | Maximum number of archived log files to retain. Oldest archives are deleted when this count is exceeded. Set to 0 to truncate the file instead of creating archives. |
Example:
const transport = new FileTransport({
filePath: '/var/log/app.log',
rotation: {
enabled: true,
maxFileSize: 52_428_800, // 50 MB
maxArchives: 10,
},
});FileRotationError
Error class thrown if rotation fails. Extends Error with a code property for error handling.
Properties:
code— Always'FILE_ROTATION_ERROR'cause— The underlying error that caused the rotation failure
Example:
try {
const transport = new FileTransport({ filePath: './logs/app.log' });
// ... use transport
} catch (err) {
if (err instanceof FileRotationError) {
console.error('Rotation failed:', err.message, 'Cause:', err.cause);
}
}Testing
File transports are typically tested by:
- Mock file system — Use dependency injection to provide a mock
fsmodule - Verify log files — Check that log entries are written to disk correctly
- Verify rotation — Trigger rotation by exceeding
maxFileSizeand verify archives are created
Example test pattern:
import { FileTransport } from '@pawells/logger-file-transport';
import { Logger } from '@pawells/logger';
import { describe, it, expect, beforeEach } from 'vitest';
describe('FileTransport', () => {
it('writes log entries to file', async () => {
const transport = new FileTransport({
filePath: './logs/test.log',
});
const logger = new Logger('test');
logger.info('Test message', { key: 'value' });
// Wait for async initialization and write
await new Promise((resolve) => setTimeout(resolve, 100));
// Assert file was created and contains log entry
// (implementation depends on test environment)
});
it('rotates file when maxFileSize is exceeded', async () => {
const transport = new FileTransport({
filePath: './logs/test.log',
rotation: {
enabled: true,
maxFileSize: 100, // Very small for testing
maxArchives: 3,
},
});
const logger = new Logger('test');
// Write entries until rotation is triggered
for (let i = 0; i < 10; i++) {
logger.info(`Message ${i}`, { index: i });
}
// Assert rotation occurred and archives were created
});
});License
MIT — see LICENSE
