UNPKG

consoleiq

Version:

Enhanced console logging with remote capabilities

240 lines (176 loc) â€ĸ 8.3 kB
# ConsoleIQ ![npm version](https://img.shields.io/npm/v/consoleiq) ![license](https://img.shields.io/npm/l/consoleiq) ![downloads](https://img.shields.io/npm/dm/consoleiq) **Enhanced console logging with remote capabilities for any JavaScript environment.** ConsoleIQ is a powerful, lightweight logging library that enhances the standard JavaScript console with features like remote logging, automatic error capturing, output colorization, and sensitive data masking. It's designed to be a drop-in replacement for the standard console, providing a consistent and feature-rich logging experience in both browser and Node.js environments. ## Core Features - 🌐 **Universal Compatibility**: Works seamlessly in browsers, Node.js, and other JavaScript runtimes. - â˜ī¸ **Remote Logging**: Send logs to any HTTP endpoint with fine-grained control over log levels. - đŸ›Ąī¸ **Automatic Error Handling**: Captures uncaught exceptions and unhandled promise rejections, providing rich contextual information. - 🎨 **Colorized Output**: Improves readability in development with customizable, color-coded log levels. - 🎭 **Data Masking**: Automatically masks sensitive data like passwords, API keys, and tokens from your logs. - đŸ“Ļ **Log Batching**: Reduces network traffic by batching logs before sending them to a remote server. - 💾 **Offline Caching**: Caches logs when offline and automatically sends them when connectivity is restored. - đŸĒļ **Lightweight & Zero-dep**: Minimal footprint with `axios` as its only dependency for remote logging. ## Installation ```bash npm install consoleiq ``` ## Quick Start ```javascript const { createConsoleIQ } = require('consoleiq'); // Initialize with default options const consoleIQ = createConsoleIQ().init(); // Use the console as you normally would console.log('This is a standard log message.'); console.info('This is an informational message.'); console.warn('This is a warning.'); console.error(new Error('This is an error.')); // Use the custom .text() method for remote logging console.text('This log will be sent to your remote endpoint.'); // When your application is shutting down, restore the original console consoleIQ.restore(); ``` --- ## Configuration ConsoleIQ is highly configurable. You can pass a configuration object to `createConsoleIQ` to tailor its behavior to your needs. ```javascript const { createConsoleIQ } = require('consoleiq'); const config = { // Remote Logging endpoint: 'https://api.your-log-service.com/logs', apiKey: 'your-secret-api-key', allowedLevels: ['error', 'warn', 'text'], // Log Batching & Caching batchSize: 20, batchInterval: 10000, // 10 seconds offlineCaching: true, // Data Masking sensitiveKeys: ['password', 'token', 'apiKey'], // Local Console Behavior colorize: true, silent: false, name: 'MyAppLogger', // Error Capturing captureGlobalErrors: true, captureUnhandledRejections: true, autoTraceErrors: true, enhanceErrors: true, }; const consoleIQ = createConsoleIQ(config).init(); ``` ### All Configuration Options | Option | Type | Default | Description | |---|---|---|---| | `endpoint` | `string` | `""` | The URL of your remote logging endpoint. | | `apiKey` | `string` | `null` | An API key to be sent as a Bearer token in the `Authorization` header. | | `allowedLevels` | `Array<string>` | `["error", "text"]` | The log levels that should be sent to the remote endpoint. | | `batchSize` | `number` | `10` | The number of logs to queue before sending them as a batch. | | `batchInterval` | `number` | `5000` | The maximum time (in ms) to wait before sending a batch, even if `batchSize` is not reached. | | `offlineCaching` | `boolean` | `true` | If `true`, logs will be cached locally (localStorage/file) if the endpoint is unreachable and sent later. | | `sensitiveKeys` | `Array<string>` | `[]` | An array of object keys whose values should be masked (replaced with `***`). | | `colorize` | `boolean` | `true` | Whether to apply colors to the local console output. | | `silent` | `boolean` | `false` | If `true`, all local console output from ConsoleIQ will be suppressed. | | `name` | `string` | `"ConsoleIQ"` | A name for the logger instance, included in remote log metadata. | | `captureGlobalErrors` | `boolean` | `true` | If `true`, captures `window.onerror` and `process.on('uncaughtException')`. | | `captureUnhandledRejections` | `boolean` | `true` | If `true`, captures unhandled promise rejections. | | `captureConsoleErrors` | `boolean` | `true` | If `true`, automatically captures calls to `console.error`. | | `autoTraceErrors` | `boolean` | `true` | If `true`, automatically adds stack traces to error logs. | | `enhanceErrors` | `boolean` | `true` | If `true`, error objects are enhanced with additional context (environment, URL, etc.). | | `maxErrorDepth` | `number` | `5` | The maximum depth for serializing error objects to prevent infinite recursion. | | `environment` | `string` | auto-detected | Manually specify the environment (`'browser'` or `'node'`). | --- ## Advanced Features ### Sensitive Data Masking Protect sensitive information by specifying keys to mask. Any value associated with these keys in logged objects will be replaced with `***`. ```javascript const consoleIQ = createConsoleIQ({ sensitiveKeys: ['password', 'token', 'apiKey'] }).init(); console.log({ user: 'test-user', password: 'my-secret-password', // Will be logged as '***' data: { token: 'another-secret' // Will also be masked } }); ``` ### Log Batching and Offline Caching For applications that generate a high volume of logs, batching can significantly reduce network overhead. If your application might run in environments with intermittent connectivity, offline caching ensures that no logs are lost. ```javascript const consoleIQ = createConsoleIQ({ endpoint: '...', batchSize: 50, // Send logs in batches of 50 batchInterval: 15000, // Or every 15 seconds offlineCaching: true, // Enable offline caching }).init(); ``` ### Automatic Error Capturing ConsoleIQ automatically captures uncaught errors and enhances them with valuable context, such as the user's browser, the page URL, and Node.js process information. This provides a more complete picture for debugging. ```javascript // Example of an enhanced error object sent to your remote endpoint { "level": "error", "message": "Error: Something went wrong", "timestamp": "2025-01-01T12:00:00.000Z", "name": "MyAppLogger", "environment": "browser", "metadata": { "type": "browser", "url": "https://example.com/my-app", "userAgent": "Mozilla/5.0...", "platform": "Win32" }, "stack": "Error: Something went wrong\n at ..." } ``` --- ## Setting Up a Custom Log Receiver You can easily create your own API endpoint to receive and process logs from ConsoleIQ. Here’s a basic example using Node.js and Express: ### 1. Install Dependencies ```bash npm install express body-parser ``` ### 2. Create the Server ```javascript // server.js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = 4000; app.use(bodyParser.json()); app.post('/logs', (req, res) => { const logs = req.body; // An array of log objects // Optional: Validate an API key const apiKey = req.headers['authorization']; if (apiKey !== 'Bearer your-secret-api-key') { return res.status(401).send('Unauthorized'); } console.log('Received logs:', JSON.stringify(logs, null, 2)); // Process the logs: save to a database, forward to another service, etc. res.status(200).send('Logs received'); }); app.listen(port, () => { console.log(`Log receiver listening at http://localhost:${port}`); }); ``` ### 3. Run the Server ```bash node server.js ``` ### 4. Configure ConsoleIQ Point ConsoleIQ to your new endpoint in your client-side or server-side application: ```javascript const consoleIQ = createConsoleIQ({ endpoint: 'http://localhost:4000/logs', apiKey: 'your-secret-api-key', }).init(); console.text('This log will be sent to your custom API.'); ``` --- ## License MIT Š 2025 ConsoleIQ ## Links - [GitHub Repository](https://github.com/consoleiq/consoleiq) - [Issues](https://github.com/consoleiq/consoleiq/issues)