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

logs-ks

v0.3.10

Published

A lightweight and developer-friendly middleware that provides structured and contextual logging for Express APIs.

Downloads

189

Readme

🛠️ Express API Middleware Logger

A lightweight and developer-friendly middleware that provides structured and contextual logging for Express APIs.

This middleware helps developers easily trace API calls, debug issues, and monitor request/response cycles by capturing detailed logs. It supports time-based log batching and works seamlessly in both development and production environments with minimal setup.


📦 Installation

Install the core logging package:

npm install logs-ks

⚙️ Quick Setup

index.ts – Initialize Logger

import express from 'express';
import { Logger } from 'logs-ks';

const app = express();

// Initialize logger with custom configuration
// Note: Logger.init() must be called before using the middleware
Logger.init({
  writeLogTime: 5, // Write logs to file every 5 minutes
  logWithEnd: true, // Default false logging response at the end of API calls
  logWithSummary: true, // Default false logging api summary like > 2025-06-13 10:11:12 | GET  200 /api/v2/user 20 ms
});

router.ts – Apply Middleware per Route

import express, { Request, Response } from 'express';
import { loggerMiddleware, LoggerContext, logEmitter } from 'logs-ks';

const router = express.Router();

// request api localhost:3000/api/foo?page=1&limit=10
router.get('/api/:id', loggerMiddleware(), async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const data = await getController(id);
    res.json(data);
  } catch (error: unknown) {
    res.status(500).send(error);
  }
});

// Use loggerMiddleware(false) to disable logging the response payload
// Useful for lightweight GET endpoints
router.get('/api/user/all', loggerMiddleware(false), (req, res) => res.json({ code: 200, payload: '...too much data' }));

async function getController(id) {
  const logger = LoggerContext.get();

  logger.addService({ type: 'DB' }, { name: 'findUser', argument: { id } });
  const findUser = await findUserDB({ id });
  logger.endService(findUser);

  return { code: 200, payload: { foo: 'bar' } };
}

// Listen for when a log file is finalized (previous file that finished writing)
// `filePath` refers to the last log file that was completed and closed
logEmitter.on('file-end', (filePath) => {
  console.log(`New log file created: ${filePath}`);
  // You can trigger backup, upload to S3, or notify devs here
});

export default router;

🧪 Example Log Output (JSON)

{
  "api": "api/foo?page=1&limit=10",
  "method": "GET",
  "authorization": null,
  "status": 200,
  "message": "OK",
  "inputTimestamp": "2025-06-13T10:11:12.000Z",
  "outputTimestamp": "2025-06-13T10:11:12.020Z",
  "processingTime": "20 ms",
  "request": {
    "headers": {},
    "params": { id: "foo"},
    "query": { page: "1", limit: "10" },
    "body": {},
    "detail": {}
  },
  "services": [{
    "id": 1,
    "type": "DB",
    "request": { "name": "findUser", "argument": { "id": "foo" } },
    "response": { "id": "foo", "name": "foobar" },
    "processingTime": "5 ms",
    "startTime": "2025-06-11T10:11:12.010Z",
    "endTime": "2025-06-11T10:11:12.015Z"
  }],
  "response": {
    "code": 200,
    "payload": { "foo": "bar" }
  },
  "summary": "2025-06-13 10:11:12 | GET  200 /api/user 20 ms"
}

type {
  api: string;
  method: string;
  authorization: string | JwtPayload | null;
  status: number;
  message: string;
  inputTimestamp: string;
  outputTimestamp: string;
  processingTime: string;
  request: {
    headers: Record<string, string>; // soon
    params: Record<string, string>;
    query: Record<string, string>;
    body: Record<string, any>;
    detail: Record<string, any>; // soon
  };
  services: Array<{
    id: number;
    type: 'DB' | 'API' | 'REDIS' | 'S3' | 'FILE' | 'FUNC';
    request: {
      name: string;
      argument: Record<string, any>;
    };
    response: Record<string, any> | Array<Record<string, any>>;
    processingTime: string;
    startTime: string;
    endTime: string;
  }>;
  response: Record<string, any>;
  summary: string;
}

🧩 Features

  • ✅ Plug-and-play Express middleware
  • 📄 Structured logs for easy debugging
  • ⏱️ Time-based file writes for performance
  • 🔍 Contextual request/response trace logging
  • 💻 Console + file output support

📁 Output

Log files will be saved automatically in the working directory (or custom location if configured via logs-ks).

  • 📂 Default path: ./logs/app-logs-${yy}-${mm}-${dd}-${hh}${mi}.jsonl
  • (e.g. logs/app-log-25-06-13-1300.jsonl)