npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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

Readme

@pawells/logger-file-transport

npm GitHub Release CI Node License: MIT

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-transport

Both packages are required: @pawells/logger-file-transport extends LogTransport from the core @pawells/logger library.

Requirements

  • Node.js >= 22.0.0
  • @pawells/logger as 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 (see IFileTransportOptions below)
  • fsModule — (Internal/Testing) Optional fs/promises module for dependency injection; defaults to Node.js fs/promises

Throws:

  • Error if 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:

  1. Mock file system — Use dependency injection to provide a mock fs module
  2. Verify log files — Check that log entries are written to disk correctly
  3. Verify rotation — Trigger rotation by exceeding maxFileSize and 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