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

request-profiler

v1.0.6

Published

A lightweight middleware for Node.js web frameworks that logs request/response details with optional persistence

Downloads

235

Readme

Request Profiler

A lightweight middleware for Node.js web frameworks that logs request/response details with optional persistence. Perfect for performance monitoring, debugging, and keeping track of your API usage patterns.

Features

  • 🚀 Framework Agnostic: Works with Express, Fastify, and other Node.js frameworks
  • 🎨 Colorized Logs: Beautiful console output with color-coded status codes
  • 💾 Persistent Storage: Save logs to JSON files or SQLite database
  • Performance Alerts: Highlight slow requests automatically
  • 🎛️ Configurable: Customize log format, storage, and thresholds
  • 📊 Lightweight: Minimal overhead and dependencies
  • 🕒 Local & ISO Timestamps: Includes timestamp and timestampLocal
  • 📅 Daily Log Splitting: Automatically creates YYYY-MM-DD.json files

Installation

npm install request-profiler

Quick Start

Express

const express = require("express");
const requestProfiler = require("request-profiler");

const app = express();

// Add the middleware
const express = require("express");
const requestProfiler = require("request-profiler");
const path = require("path");

const app = express();

// Add the middleware
app.use(requestProfiler({ 
  storage: 'json',
  storagepath: path.resolve('C:/Users/xyz/OneDrive/Documents/merger_safe'), // windows / macOS / linux friendly
  slowThreshold: 200,
  format: 'text',
  daily: true,      // <-- auto-create 2025-12-06.json, etc.
  // maxLines: 2000 // optional: only trims when provided
}));

app.get("/api/users", (req, res) => {
  res.json({ users: ["Alice", "Bob"] });
});

app.listen(3000);


app.get("/api/users", (req, res) => {
  res.json({ users: ["Alice", "Bob"] });
});

app.listen(3000);

Fastify

const fastify = require('fastify')();
const requestProfiler = require("request-profiler");

// Create the middleware once
const profiler = requestProfiler({
  storage: "json",
  daily: true,
});

fastify.addHook('onRequest', (request, reply, done) => {
  profiler(request.raw, reply.raw, done);
});

fastify.get('/api/users', async () => {
  return { users: ['John', 'Jane'] };
});

await fastify.listen({ port: 3000 });

Configuration Options

| Option | Type | Default | Description | | ----------------------------- | ----------------- | --------------- | ------------------------------------- | | storage | string\|boolean | false | 'json', 'sqlite', or false | | storagepath / storagePath | string | null | Directory or full file path for logs | | slowThreshold | number | 500 | Mark requests slower than this (ms) | | format | string | 'text' | 'text', 'json', or 'both' | | daily | boolean | false | Auto-create logs as YYYY-MM-DD.json | | maxLines | number | undefined | Only trims logs if provided | | logFile | string | 'logs.ndjson' | Fallback filename when daily=false | | dbFile | string | 'logs.db' | SQLite filename | | silent | boolean | false | Disable console output |

Examples

Basic Usage

app.use(requestProfiler());

JSON Storage with Custom Threshold

app.use(requestProfiler({
  storage: "json",
  slowThreshold: 200,
  logFile: "api-logs.json"
}));

SQLite Storage with JSON Output

app.use(requestProfiler({
  storage: "sqlite",
  format: "both",
  dbFile: "performance.db"
}));

Silent Mode (Storage Only)

app.use(requestProfiler({
  storage: "sqlite",
  silent: true
}));

Console Output

The middleware produces colorized console logs:

[01:25:14] GET /api/users → 200 OK (45 ms)
[01:25:15] POST /api/users → 201 Created (123 ms)
[01:25:16] GET /api/slow → 200 OK (678 ms) [SLOW]
[01:25:17] GET /api/missing → 404 Not Found (12 ms)
[01:25:18] POST /api/error → 500 Internal Server Error (5 ms)

Color Coding:

  • 🟢 Green: 2xx status codes (success)
  • 🟡 Yellow: 4xx status codes (client errors)
  • 🔴 Red: 5xx status codes (server errors)
  • 🔴 Red: Slow requests (above threshold)

Storage Formats

JSON File Storage

Logs are stored as an array of objects:

[
  {
    "timestamp": "2025-12-06T01:25:14.123Z",
    "timestampLocal": "12/6/2025, 6:55:14 AM",
    "method": "GET",
    "path": "/api/users",
    "status": 200,
    "durationMs": 45,
    "userAgent": "Mozilla/5.0...",
    "ip": "::1"
  }
]

SQLite Storage

Logs are stored in a request_logs table with the following schema:

CREATE TABLE request_logs (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  timestamp TEXT NOT NULL,
  method TEXT NOT NULL,
  path TEXT NOT NULL,
  status INTEGER NOT NULL,
  duration_ms INTEGER NOT NULL,
  user_agent TEXT,
  ip TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

Advanced Usage

Accessing Stored Logs

const requestProfiler = require("request-profiler");
const StorageManager = require("request-profiler/lib/storage");

// Create storage instance
const storage = new StorageManager({
  storage: "sqlite",
  dbFile: "logs.db"
});

// Initialize and get recent logs
await storage.init();
const recentLogs = await storage.getLogs(50); // Get last 50 logs
console.log(recentLogs);

Custom Log Analysis

// Example: Find slow endpoints
const logs = await storage.getLogs(1000);
const slowEndpoints = logs
  .filter(log => log.durationMs > 500)
  .sort((a, b) => b.durationMs - a.durationMs);

console.log('Slowest endpoints:', slowEndpoints.slice(0, 10));

Use Cases

  • Development: Monitor API performance during development
  • Debugging: Identify slow endpoints and bottlenecks
  • Performance Monitoring: Track response times over time
  • Analytics: Analyze usage patterns and popular endpoints
  • Error Tracking: Monitor error rates and status codes

Requirements

  • Node.js >= 14.0.0
  • Compatible with Express, Fastify, and other Node.js HTTP frameworks