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

terminal-structured-logger

v1.0.2

Published

Adds validation, correlation IDs, throttling, optional JSON-style lines, and redaction on top of terminal-pretty-logger—same sink, richer controls.

Readme

terminal-structured-logger

Thin layer over terminal-pretty-logger: you keep the same console-oriented pipeline, but gain stricter inputs, request-scoped IDs, optional flood control, machine-readable lines when you need them, and small helpers for env and timing.

Installation

npm install terminal-structured-logger

Quick Start

import logger from "terminal-structured-logger";

logger.info("Application started");
logger.debug("Debug data", { userId: 1 });
logger.warn("Deprecation notice");
logger.error("Something failed", new Error(" details"));

Features

  • Strict messages — Non-string and empty strings are rejected; oversized payloads are blocked
  • Redaction — Built-in patterns hide secrets, tokens, and card-like number runs
  • Correlation — Attach or auto-generate trace IDs for cross-service trails
  • Flood control — Sliding window caps so bursts cannot overwhelm the console or downstream collectors
  • Machine-readable mode — Optional JSON lines per entry for stacks like ELK, Loki, or CloudWatch
  • Scoped children — Prefix and trace-scoped child loggers without new wiring
  • TimingstartTimer, endTimer, measureAsync for latency-friendly logs
  • Test capture — Buffer emitted entries for assertions; strip ANSI when comparing strings

API

Logger

Default export

import logger from "terminal-structured-logger";

logger.trace(message: string, ...args: unknown[]): void
logger.debug(message: string, ...args: unknown[]): void
logger.info(message: string, ...args: unknown[]): void
logger.warn(message: string, ...args: unknown[]): void
logger.error(message: string, ...args: unknown[]): void
logger.fatal(message: string, ...args: unknown[]): void
logger.log(level: LogLevel, message: string, ...args: unknown[]): void

Factory & configuration

import { createLogger, getLogger, ChangelogUtilsLoggerOptions } from "terminal-structured-logger";

// Create a new logger with options
const log = createLogger({
  prefix: "[MyApp]",
  minLevel: "info",
  rateLimitMs: 1000,
  maxRateLimitBurst: 10,
  structured: true,
  traceId: "req-123",
});

// Get or create singleton
const log2 = getLogger({ prefix: "[Global]" });

ChangelogUtilsLoggerOptions

| Option | Type | Default | Description | |--------|------|---------|-------------| | prefix | string | "" | Prepended to all messages | | suffix | string | "" | Appended to all messages | | minLevel | LogLevel | "trace" | Minimum level to emit | | sanitizePatterns | RegExp[] | Built-in | Patterns for redaction | | rateLimitMs | number | 0 | Rate limit window (ms); 0 = disabled | | maxRateLimitBurst | number | 100 | Max logs per window | | structured | boolean | false | Output JSON lines | | traceId | string | "" | Correlation ID for all logs |

Extended methods

// Child logger with extra prefix
const childLog = logger.child("[Auth]");

// Child logger with trace ID (auto-generated if omitted)
const tracedLog = logger.withTraceId();
const tracedLog2 = logger.withTraceId("custom-id");

// Conditional log
logger.when(process.env.DEBUG === "1", "debug", "Debug info");

// Group key-value pairs
logger.group("Config", { host: "localhost", port: 3000 });

// Batch log multiple messages
logger.batch("info", ["Line 1", "Line 2", "Line 3"]);

// Log table-like data
logger.table([{ id: 1, name: "a" }, { id: 2, name: "b" }]);

Timer utilities

import { startTimer, endTimer, measureAsync, formatDuration } from "terminal-structured-logger";

// Manual timer
startTimer("fetch");
await fetchData();
const ms = endTimer("fetch");
console.log(`Took ${formatDuration(ms)}`);

// Async wrapper with auto-log
const result = await measureAsync("api-call", () => fetch(url));

Standalone utilities

import {
  generateTraceId,
  formatDuration,
  parseDuration,
  loadEnv,
  loadEnvAndLog,
  colorizeLevel,
  stripColors,
  type LogLevel,
} from "terminal-structured-logger";

generateTraceId(21);           // "V1StGXR8_Z5jdHi6B-myT"
formatDuration(1500);         // "1.5s"
parseDuration("2m");          // 120000
loadEnv();                    // Load .env, return parsed object
loadEnvAndLog(".env", (keys) => console.log("Loaded:", keys));
colorizeLevel("error");       // Chalk-red "ERROR"
stripColors("\x1b[31mred\x1b[0m");  // "red"

Log capture (testing)

import {
  enableLogCapture,
  disableLogCapture,
  getCapturedLogs,
  getPlainCapturedLogs,
  clearCapturedLogs,
} from "terminal-structured-logger";

enableLogCapture();
logger.info("test message");
const logs = getCapturedLogs();
const plain = getPlainCapturedLogs();  // ANSI stripped
disableLogCapture();
clearCapturedLogs();

TypeScript

The package ships with type definitions. No @types needed.

import logger, { LogLevel, ChangelogUtilsLoggerOptions, LogEntry } from "terminal-structured-logger";

License

ISC