console-guard
v1.0.0
Published
A production-grade utility for globally managing console methods via monkey-patching.
Maintainers
Readme
console-guard
A production-grade utility for globally managing console methods. console-guard allows you to silence specific log levels in production environments without modifying your original source code or affecting Git history.
Purpose
Logging is essential during development but can be noisy, reveal internal application state, or impact performance in production. console-guard provides a centralized way to control console output based on the environment and specific log levels.
Key Features
- Selective Silencing: Specify exactly which methods (
log,info,debug,warn,error) should be muted. - Whitelist Support: Explicitly exclude certain methods from being silenced, even if they match a silenced group.
- Developer Bypass: A "Secret Trapdoor" allows developers to re-enable all logs in production temporarily via a
localStoragetoggle. - Execution Context Safety: Fully compatible with Server-Side Rendering (SSR) and Node.js environments.
- No Side Effects: Replaces original methods with empty functions (
noop) to ensure call-site stability.
Installation
Install via your preferred package manager (once published):
npm install console-guardFor local development or integration from source:
- Clone the repository.
- Run
npm install. - Run
npm run buildto generate thedistfolder.
Usage
Import and initialize the utility at the very top of your application's entry point (e.g., index.ts, main.ts, or App.tsx).
import { initConsoleGuard } from 'console-guard';
initConsoleGuard({
enabled: process.env.NODE_ENV === 'production',
levels: ['log', 'info', 'debug'],
exclude: ['error']
});Configuration
The initConsoleGuard function accepts a configuration object of type ConsoleGuardConfig:
| Property | Type | Description |
| :--- | :--- | :--- |
| enabled | boolean | Determines if the guard should active. If false, the utility exits early. |
| levels | string[] | An array of console methods to overwrite (e.g., ['log', 'info']). |
| exclude | string[] | (Optional) An array of methods to whitelist, ensuring they are never silenced. |
The "Secret Trapdoor" (Bypass)
To enable debugging in a live production environment, console-guard checks for a specific key in the browser's localStorage.
- Open the browser's DevTools.
- Go to the Application tab.
- Select Local Storage from the sidebar.
- Add a new key:
__CONSOLE_GUARD_REVEAL__. - Set its value to
true. - Refresh the page.
All logs will now be visible, regardless of the enabled or levels configuration.
Environment Compatibility
console-guard is designed to run in both browser and server environments. It performs safety checks for window and console availability before attempting to apply any monkey-patches or access localStorage.
License
MIT
