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

@shy-dev/node-audit-logger

v1.1.0

Published

Node.js middleware and logger to track user activity logs in MongoDB.

Readme

Node Audit Logger

A fully ready-to-publish npm package for Node.js applications to track user activity logs. It supports multiple projects with separate MongoDB clusters and provides an Express middleware plus a custom event logger.

Installation

npm install @shy-dev/node-audit-logger

Usage

1. Initialize Middleware

In your Express app, initialize the logger before defining routes:

import express from 'express';
import { init, LoggerScope } from '@shy-dev/node-audit-logger';

const app = express();
app.use(express.json());

// Initialize and use the middleware
const auditMiddleware = await init({
  mongoUri: process.env.MONGO_URI, // Your MongoDB connection string
  jwtSecret: process.env.JWT_SECRET, // Optional: for decoding JWTs automatically
  consoleLoggerScope: LoggerScope.ALL, // Optional: Control console output (ALL, SERVER_ONLY, WORKER_ONLY, NONE)
  options: {
    skipPaths: ['/health', '/metrics'], // Paths to skip logging
    maskRequest: true,      // Mask sensitive data in request
    maskResponse: true,     // Mask sensitive data in response
    logPaginatedResponse: 'partial', // 'full', 'partial', 'none', or false
    // Optional: Enable Queue
    // useQueue: true,
    // queueOptions: { host: '127.0.0.1', port: 6379 }
  }
});

app.use(auditMiddleware);

app.listen(3000, () => console.log('Server running'));

2. Explicit User ID Setting

Sometimes the user ID is not available in the request headers (e.g., during login or registration). You can explicitly set the user ID for the current request using the setAuditUserId helper:

import { setAuditUserId } from '@shy-dev/node-audit-logger';

app.post('/login', async (req, res) => {
  const user = await loginUser(req.body);
  
  // Explicitly link this request log to the user
  setAuditUserId(res, user.id);
  
  res.json({ token: '...' });
});

3. Manual Event Logging

You can also log custom events that are not tied to HTTP requests:

import { logEvent } from '@shy-dev/node-audit-logger';

await logEvent({
  userId: 'user-id',
  type: 'SYSTEM',
  action: 'CRON_JOB',
  actionMessage: 'Daily cleanup completed',
  metadata: { itemsProcessed: 100 }
});

Configuration Options

Init Options (init)

| Option | Type | Default | Description | |---|---|---|---| | mongoUri | string | Required | MongoDB connection string. | | jwtSecret | string | undefined | JWT secret for decoding tokens from Authorization header. | | options | AuditLoggerOptions | {} | Middleware configuration options (see below). | | consoleLoggerScope | LoggerScope | ALL | Controls console output. Options: ALL, SERVER_ONLY, WORKER_ONLY, NONE. |

Middleware Options (options)

| Option | Type | Default | Description | |---|---|---|---| | skipPaths | string[] | [] | List of paths to exclude from logging (prefix match). | | maskRequest | boolean | true | Whether to mask sensitive data (password, token, etc.) in request body/headers. | | maskResponse | boolean | true | Whether to mask sensitive data in response body. | | logPaginatedResponse | 'full' \| 'partial' \| 'none' \| false | 'full' | Controls response logging. 'partial' truncates large arrays. 'none' or false skips response body. | | useQueue | boolean | false | If true, logs are sent to a Redis queue instead of saving directly. | | queueOptions | object | undefined | Redis connection options for BullMQ (e.g., { host: 'localhost', port: 6379 }). Required if useQueue is true. | | startWorker | boolean | false | If true, automatically starts the queue worker in the same process. | | customModel | Mongoose Model | undefined | A custom Mongoose model to use for saving logs. |

Advanced Features

Queue Support (Redis)

To offload log saving to a background process, enable the queue:

  1. Configure Middleware:

    const auditMiddleware = await init({
      mongoUri: process.env.MONGO_URI,
      options: {
        useQueue: true,
        queueOptions: { host: '127.0.0.1', port: 6379 }
      }
    });
  2. Run Worker: You can either start the worker automatically by setting startWorker: true in options, or run it in a separate process:

    // worker.ts
    import { startWorker } from '@shy-dev/node-audit-logger';
    
    const MONGO_URI = process.env.MONGO_URI;
    const REDIS_OPTIONS = { host: '127.0.0.1', port: 6379 };
    
    startWorker(MONGO_URI, REDIS_OPTIONS).catch(console.error);

Custom Mongoose Model

You can provide your own Mongoose model to save logs to a custom collection or with a custom schema.

  1. Define Your Model:

    import mongoose from 'mongoose';
    
    const mySchema = new mongoose.Schema({
      // ... your custom schema fields
    }, { strict: false });
    
    const MyCustomLog = mongoose.model('MyCustomLog', mySchema);
  2. Pass to Middleware:

    const auditMiddleware = await init({
      mongoUri: process.env.MONGO_URI,
      options: {
        customModel: MyCustomLog
      }
    });

Sensitive Data Masking

The logger automatically masks sensitive fields in requests and responses. By default, it looks for keys like: password, token, authorization, secret, creditCard, cvv, ssn, etc.

You can toggle this behavior using maskRequest and maskResponse options.

License

MIT