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

@euclidean-dev/console-override

v1.1.1

Published

Override console methods to control the output

Downloads

28

Readme

console-override

A powerful, flexible console management library for controlling and enhancing console output in JavaScript/TypeScript applications.

Install

npm i @euclidean-dev/console-override

Quick Start

Most common use case - disable all console output in production:

import { ConsoleOverride } from "@euclidean-dev/console-override";

// Simple: disable all console methods
ConsoleOverride.configure();

// Or: only in production
ConsoleOverride.configure({
  enabled: process.env.NODE_ENV === "production",
});

// Keep certain methods (like errors)
ConsoleOverride.configure({
  exclude: ["error", "warn"],
});

That's it! The above covers 90% of typical usage.

Core Options

ConsoleOverride.configure({
  enabled: true,              // Enable/disable the override (default: true)
  exclude: ["error"],         // Methods to keep working (default: [])
  clearOnLoad: true,          // Clear console on load (default: false)
  debugKey: "debug",          // Disable via localStorage key=true (default: undefined)
});

Advanced Features

Everything below is optional and for advanced use cases. You don't need any of this for basic console control.

Namespace Filtering

Filter console messages based on namespace patterns in the first argument:

// Your code
console.log("[auth]", "User logged in");
console.log("[analytics]", "Event tracked", event);
console.log("[debug]", "Debug info");

// Only show [auth] logs, hide [analytics]
ConsoleOverride.configure({
  includeNamespaces: ["[auth]"],
  excludeNamespaces: ["[analytics]"],
});

Options:

  • includeNamespaces: Array of prefixes to allow. Only logs starting with these are shown.
  • excludeNamespaces: Array of prefixes to block. These logs are hidden.

Behavior:

  • excludeNamespaces is checked first and takes precedence
  • Non-string first arguments are not affected by namespace filtering

Custom Hooks

Hooks let you intercept and process console calls with custom logic:

type ConsoleHook = (method: Methods, args: unknown[]) => void | "passthrough" | "mute";

Return values:

  • void/undefined: Continue normal processing
  • "passthrough": Allow the log, skip remaining hooks
  • "mute": Block the log completely

Hook Examples

Redact sensitive data:

const redactSensitiveData = (method, args) => {
  const patterns = [
    /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,  // emails
    /\btoken[_-]?\w+/gi,  // tokens
  ];
  
  args.forEach((arg, index) => {
    if (typeof arg === "string") {
      patterns.forEach(pattern => {
        args[index] = arg.replace(pattern, "[REDACTED]");
      });
    }
  });
};

ConsoleOverride.configure({
  hooks: [redactSensitiveData],
});

Forward errors to Sentry:

const forwardToSentry = (method, args) => {
  if (method === "error") {
    fetch("/api/logs", {
      method: "POST",
      body: JSON.stringify({ level: method, message: args }),
    });
  }
};

ConsoleOverride.configure({
  hooks: [forwardToSentry],
});

Filter by message pattern:

const filterByPattern = (method, args) => {
  const firstArg = args[0];
  
  // Block logs containing "SECRET"
  if (typeof firstArg === "string" && firstArg.includes("SECRET")) {
    return "mute";
  }
  
  // Only allow logs matching pattern
  if (typeof firstArg === "string" && /^\[important\]/.test(firstArg)) {
    return "passthrough";
  }
};

Combine multiple hooks:

ConsoleOverride.configure({
  hooks: [
    redactSensitiveData,
    forwardToSentry,
    filterByPattern,
  ],
});

Prefix & Suffix Metadata

Automatically add contextual information to every log message.

Prefix Configuration

Add metadata at the beginning of each log:

ConsoleOverride.configure({
  prefix: {
    includeTimestamp: "time",      // "off" | "time" | "iso" | "elapsed"
    includeLevel: true,            // Add [LOG], [ERROR], etc.
    includeEnv: true,              // Add [DEV], [PROD], etc.
    includeNamespace: true,        // Extract [namespace] from first arg
    custom: (ctx) => `[v1.2.3]`,  // Custom prefix function
  },
});

Timestamp options:

  • "off": No timestamp (default)
  • "time": 10:23:01.123
  • "iso": 2025-11-17T10:23:01.123Z
  • "elapsed": +123ms (time since previous log)

Example output:

console.log("[auth]", "User logged in");
// Output: 10:23:01.123 [LOG] [DEV] [auth] User logged in

Suffix Configuration

Add metadata at the end of each log:

ConsoleOverride.configure({
  suffix: {
    includeCorrelationId: true,           // Add (req: 1234-5678)
    includeUserId: true,                  // Add (user: 42) or (anon)
    includeStackSnippetFor: ["error"],    // Add stack trace for specific methods
    custom: (ctx) => "(LOG-1234)",        // Custom suffix function
  },
});

Setting global context for suffix:

// Set these anywhere in your app
globalThis.__correlationId = "req-abc-123";
globalThis.__userId = 42;

console.log("Processing payment");
// Output: Processing payment (req: req-abc-123) (user: 42)

Example with stack trace:

ConsoleOverride.configure({
  suffix: {
    includeStackSnippetFor: ["error", "warn"],
  },
});

console.error("Something went wrong");
// Output: Something went wrong at MyComponent.tsx:45

Combining Prefix & Suffix

ConsoleOverride.configure({
  prefix: {
    includeTimestamp: "time",
    includeLevel: true,
  },
  suffix: {
    includeCorrelationId: true,
    includeUserId: true,
  },
});

console.log("Processing payment");
// Output: 10:23:01.123 [LOG] Processing payment (req: req-abc-123) (user: 42)

Execution Order

When multiple features are configured, they execute in this order:

  1. Namespace filtering - Applied first
  2. Hooks - Executed in array order
  3. Prefix/Suffix - Added to output
  4. Original console method - Called with modified args

If namespace filtering blocks the log, nothing else runs. If a hook returns "mute", the log is blocked. If a hook returns "passthrough", remaining hooks are skipped.


TypeScript Support

Full TypeScript definitions are included:

import { ConsoleOverride, Configuration, ConsoleHook, PrefixConfig, SuffixConfig } from "@euclidean-dev/console-override";

License

MIT