log-capture
v1.0.3
Published
Intercept console methods
Readme
log-capture
A lightweight JavaScript library for intercepting browser console methods. My first npm package 😅☺️
Installation
pnpm add log-captureOr with npm:
npm install log-captureQuick Start
import { capture } from 'log-capture'
capture.on('log', (original, ...args) => {
// Handle the intercepted log
original(...args)
})
capture.start()
console.log('Hello world')The original console methods are preserved and can be called through the original function provided to each listener.
Use Cases
log-capture can be used as a foundation for different console-related features, such as:
- Remote logging — send browser logs and errors to a remote server for monitoring and debugging.
- Visual console — display console messages directly inside the application's DOM, useful for dashboards, development tools, and embedded applications.
- Hide logs — prevent selected logs, warnings, or errors from being displayed in the browser console.
- Log filtering — filter messages based on their method, content, or custom application rules.
- Error monitoring — collect errors and warnings and send them to an external monitoring service.
- Custom logging — transform or process console messages before passing them to the original console method.
Supported Methods
log-capture currently intercepts:
logwarntablecleardebugerror
Listening to Console Methods
Use on() to add one or more listeners.
capture.on('error', (original, ...args) => {
saveError(args)
original(...args)
})Multiple listeners can be registered for the same method:
capture.on('log', listener1, listener2)Important
Do not call an intercepted console method inside a listener:
// Do not do this
capture.on('log', (...args) => {
console.log(...args)
})This can cause an infinite interception loop.
If you want to keep the original console behavior, use the original function:
capture.on('log', (original, ...args) => {
saveLog(args)
original(...args)
})Removing Listeners
Use off() to remove specific listeners:
const handleError = (original, ...args) => {
saveError(args)
original(...args)
}
capture.on('error', handleError)
capture.off('error', handleError)To remove all listeners for a method:
capture.off('error')Start and Stop
Start interception with start():
capture.start()Stop interception with stop():
capture.stop()When stopped, the original console methods are restored.
EventListener Aliases
addEventListener() and removeEventListener() are aliases for on() and off().
capture.addEventListener('warn', handleWarning)
capture.removeEventListener('warn', handleWarning)Checking the Capture State
Use isCapturing to check whether interception is active:
if (capture.isCapturing) {
// Capture is active
}Registered listeners are available through listeners:
console.log(capture.listeners)License
MIT
