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 🙏

© 2025 – Pkg Stats / Ryan Hefner

express-audit-logger

v0.1.7

Published

A flexible audit logging middleware for Express applications

Readme

express-audit-logger

NPM Version

A flexible and powerful audit logging middleware for Express applications built with TypeScript. Track user actions, API activity, and system events with customizable storage providers and extensive configuration options.

Features

  • Easy to integrate Express middleware
  • Automatic HTTP request/response logging
  • Sensitive data masking
  • Path exclusion patterns
  • Response time tracking
  • Pluggable storage providers
  • Detailed request metadata logging
  • Manual logging capability
  • Written in TypeScript with full type support

Installation

    npm install express-audit-logger
    # or
    yarn add express-audit-logger

Quick Start

    import express from 'express';
    import { AuditLogger, ConsoleStorageProvider } from 'express-audit-logger';
    
    const app = express();
    
    // Create an audit logger instance
    const auditLogger = new AuditLogger({
      storageProvider: new ConsoleStorageProvider(),
      maskSensitiveData: true,
      sensitiveFields: ['password', 'token'],
      excludePaths: ['/health', '/metrics']
    });
    
    // Use as middleware
    app.use(auditLogger.middleware());
    
    // Example route with manual logging
    app.post('/users', async (req, res) => {
      // Your business logic here
      await auditLogger.log('CREATE_USER', {
        userId: req.body.id,
        email: req.body.email
      });
      res.send({ success: true });
    });

Configuration Options

The AuditLogger constructor accepts an options object with the following properties:

    interface AuditLoggerOptions {
      storageProvider: AuditStorageProvider;  // Required
      excludePaths?: string[];               // Optional
      maskSensitiveData?: boolean;          // Optional
      sensitiveFields?: string[];           // Optional
    }

Storage providers

The library comes with two built-in storage providers

Console Storage Provider

You can use the console storage provider to display your logs on the console

    import { ConsoleStorageProvider } from 'express-audit-logger';

    const logger = new AuditLogger({
      storageProvider: new ConsoleStorageProvider()
    });
File Storage Provider

You can use the file storage provider to save your logs in a file

    import { FileStorageProvider } from 'express-audit-logger';
    
    const logger = new AuditLogger({
      storageProvider: new FileStorageProvider('./audit-logs.txt')
    });
Custom Storage Provider

You can create your own storage provider by implementing the AuditStorageProvider interface:

    import { AuditLog, AuditStorageProvider } from 'express-audit-logger';
    import { MongoClient } from 'mongodb';
    
    class MongoStorageProvider implements AuditStorageProvider {
      private client: MongoClient;
      private collection: string;
    
      constructor(client: MongoClient, collection: string) {
        this.client = client;
        this.collection = collection;
      }
    
      async save(log: AuditLog): Promise<void> {
        await this.client
          .db()
          .collection(this.collection)
          .insertOne(log);
      }
    }
Path Exclusion

Exclude specific paths from being logged:

    const logger = new AuditLogger({
    storageProvider: new ConsoleStorageProvider(),
     excludePaths: [
        '/health',           // Excludes health checks
        '/static',           // Excludes all static files
        '/api/v1/metrics',   // Excludes metrics endpoint
        '/favicon.ico'       // Excludes favicon requests
      ]
    });
Sensitive Data Masking

Mask sensitive information in logs:

    const logger = new AuditLogger({
      storageProvider: new ConsoleStorageProvider(),
      maskSensitiveData: true,
      sensitiveFields: ['password', 'token', 'creditCard']
    });
Log Structure

Each audit log entry contains the following information:

    interface AuditLog {
      timestamp: Date;
      userId?: string;
      action: string;
      resource: string;
      details: Record<string, any>;
      ip?: string;
      userAgent?: string;
      status?: number;
      method?: string;
      path?: string;
    }
Manual Logging

In addition to automatic request logging, you can manually create log entries:

    // Inside an async route handler or middleware
    await auditLogger.log('USER_LOGIN', {
      userId: '123',
      email: '[email protected]',
      loginMethod: 'oauth'
    });
Error Handling

The logger will never throw errors that could interrupt your application flow. All storage errors are caught and logged to console

    try {
      await storageProvider.save(log);
    } catch (error) {
      console.error('Failed to save audit log:', error);
    }

Examples

Basic Setup

Basic express app setup

    import express from 'express';
    import { AuditLogger, ConsoleStorageProvider } from 'express-audit-logger';
    
    const app = express();
    app.use(express.json());
    
    const logger = new AuditLogger({
      storageProvider: new ConsoleStorageProvider()
    });
    
    app.use(logger.middleware());
With Database Storage

You can create use your custom custom storage provider (e.g for MongoDB or PostgresQL)

    import { AuditLogger } from 'express-audit-logger';
    import { MongoStorageProvider } from './mongo-provider';
    import { MongoClient } from 'mongodb';
    
    const client = new MongoClient('mongodb://localhost:27017');
    await client.connect();
    
    const logger = new AuditLogger({
      storageProvider: new MongoStorageProvider(client, 'audit_logs')
    });
    
    app.use(logger.middleware())
Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request