@euclidean-dev/console-override
v1.1.1
Published
Override console methods to control the output
Downloads
28
Maintainers
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-overrideQuick 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:
excludeNamespacesis 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 inSuffix 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:45Combining 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:
- Namespace filtering - Applied first
- Hooks - Executed in array order
- Prefix/Suffix - Added to output
- 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
