The fastest, most elegant logging library for Node.js, TypeScript, Bun, and Deno
Spectral is a high-performance, zero-dependency logging library designed to replace console.log with beautiful colors, advanced formatting, and incredible speed.
Official Website | Documentation Docs | Roadmap Roadmap | VS Code Extension
- Lightning Fast - Optimized stdout writing with internal buffering
- Rich Colors - Full support for HEX, RGB, and named colors with automatic terminal detection
- JSON Logging - Structured JSON output with file rotation and scopes with the FileLoggerPlugin
- VS Code Extension with snippets, playground and configuration generator.
- TypeScript First - Complete type safety and IntelliSense support
- Smart Error Handling - Automatic error tracking, stack trace cleaning, and duplicate detection
- Plugin System - Extensible architecture for custom functionality
- Zero Dependencies - Minimal footprint, maximum performance
- CLI Tools - Built-in diagnostics, benchmarking, and configuration management
SpectralLogs continues to outperform other popular loggers in both speed and memory efficiency, thanks to recent GC optimizations and warm-up handling.
Ops/sec (higher is better)
SpectralLogs | ████████████████████████████████ 1,187,120
Console | ███████████████████████ 675,645
Pino | ██████████████ 236,886
Log4js | ███████ 102,826
Winston | ████ 72,133Memory Usage (lower is better)
Console | 0.03 MB █
SpectralLogs | 0.19 MB █
Log4js | 0.34 MB ██
Pino | 0.46 MB ███
Winston | 5.55 MB ██████████████████████⚡ SpectralLogs is now ~43% faster than
console.logand up to 94% faster than Winston, while keeping memory usage extremely low at just 0.19 MB.
SpectralLogs is actively developed with exciting features on the horizon! Check out our interactive roadmap to see what's planned:
- v0.2.0: Performance improvements and stability enhancements
- v0.3.0: Advanced logging features (structured logging, filtering, tracing)
- v0.4.0: Rich plugin ecosystem and analytics
- v0.5.0: Enhanced developer experience with advanced tooling
- v1.0.0: Production-ready with enterprise features
npm install spectrallogsbun add spectrallogsEnable npm specifiers in deno.json and import:
// deno.json
{
"nodeModulesDir": true
}
// main.ts
import spec from 'npm:spectrallogs';
spec.info('Deno ready');import spec from 'spectrallogs';
spec.log('Hello Spectral!');
spec.info('Informational message');
spec.success('Operation completed!');
spec.warn('Warning message');
spec.error('Error occurred');
spec.debug('Debug information');Spectral supports multiple color formats:
// HEX colors
spec.log('Custom message', '#07d53a');
// RGB colors
spec.info('Blue message', 'rgb(0, 191, 255)');
// Named colors
spec.warn('Orange warning', 'orange');black, red, green, yellow, blue, magenta, cyan, white, gray, grey, orange, purple, pink, brown, lime, navy, teal, olive, maroon
import spec from 'spectrallogs';
spec.configure({
showTimestamp: true,
showLevel: true,
debugMode: false,
bufferWrites: true, // enable/disable stdout buffering in Node (default true outside tests)
codec: 'utf-8',
timeFormat: 'iso', // 'iso' | 'unix' | 'locale'
colors: {
info: '#00bfff',
success: '#00ff88',
warn: '#ffaa00',
error: '#ff5555',
log: '#dddddd',
debug: '#cc66ff',
},
});Spectral lets you color inline segments and register custom color names.
- Node and Web expose
spec.color(text, nameOrColor)for template strings. - You can also register custom names via
spec.color.add(name, color).
// Node / Bun / Deno
import spec from 'spectrallogs';
// Register custom colors
spec.color.add('accent', '#7c3aed'); // purple-600
spec.color.add('muted', '#9ca3af'); // gray-400
// Built-in names also work: 'info' | 'success' | 'warn' | 'error' | 'log' | 'debug'
spec.info(`${spec.color('Accent Title', 'accent')} - details with ${spec.color('muted text', 'muted')}`);
// Any CSS-like color is accepted: #hex, rgb(...), or named (orange, teal, ...)
spec.log(`${spec.color('Only this label is blue:', 'rgb(0,191,255)')} rest uses log color`);// Web (ESM)
import spec from 'spectrallogs/web';
spec.color.add('accent', '#7c3aed');
spec.color.add('muted', '#9ca3af');
// Inline segments render as separate %c parts; unmarked text uses the default message color
spec.info(`${spec.color('Accent Title', 'accent')} - details with ${spec.color('muted text', 'muted')}`);
// Per-call color sets the default message color for unmarked text
spec.info(`Default cyan, but ${spec.color('accent span', 'accent')} here`, '#22d3ee');
// Configure level colors globally
spec.configure({ colors: { info: '#22d3ee' } });Notes:
- Node preserves the outer message color across inline segments.
- Web splits the message into
%csegments so only marked spans change color; the rest uses the message/default level color.
Spectral includes a powerful plugin system for extending functionality.
Save logs to files with automatic rotation and structured JSON formatting:
import spec, { FileLoggerPlugin } from 'spectrallogs';
// Basic file logging
const fileLogger = new FileLoggerPlugin({
filePath: './logs/app.log',
maxSize: 10 * 1024 * 1024, // 10MB
rotate: true,
});
spec.use(fileLogger);
spec.info('User logged in');// Structured JSON logging
spec.use(new FileLoggerPlugin({
filePath: './logs/application.log',
format: 'json', // Output as structured JSON
handleScope: true, // Include child logger scope information
}));
// Multiple log files for different purposes
const generalLogger = new FileLoggerPlugin({
filePath: './logs/general.log',
format: 'json'
});
const errorLogger = new FileLoggerPlugin({
filePath: './logs/errors.log',
format: 'json'
});
spec.use(generalLogger);
spec.use(errorLogger);
// Child logger integration
const apiLogger = spec.child('api');
apiLogger.use(new FileLoggerPlugin({
filePath: './logs/api.log',
format: 'json'
}));
apiLogger.info('API request');Produces structured JSON output:
{
"timestamp": "2024-01-15T10:30:00.000Z",
"level": "info",
"message": "User logged in",
"scope": "api"
}interface FileLoggerOptions {
filePath?: string; // Path to log file
maxSize?: number; // Max file size before rotation (default: 10MB)
rotate?: boolean; // Enable log rotation (default: true)
format?: 'json' | 'text'; // Output format (default: 'json')
handleScope?: boolean; // Include logger scope (default: true)
}- Structured JSON: Rich, queryable log data
- Automatic Rotation: Prevents log files from growing too large
- Child Logger Support: Proper scope inheritance and isolation
- Multiple Instances: Run multiple file loggers simultaneously
- Performance Optimized: Efficient streaming with minimal overhead
Track logging performance metrics:
import spec, { PerformanceTrackerPlugin } from 'spectrallogs';
const perfTracker = new PerformanceTrackerPlugin();
spec.use(perfTracker);
spec.log('Log message 1');
spec.info('Log message 2');
spec.success('Log message 3');
perfTracker.printStats();With TypeScript:
import spec from "spectrallogs"
import { Plugin } from 'spectrallogs';
const myPlugin: Plugin = {
name: 'MyCustomPlugin',
init() {
console.log('Plugin initialized');
},
beforeLog(message: string, level: any, options: any) {
return message.toUpperCase();
},
afterLog(message: any, level: any, options: any) {
console.log('Log completed');
},
};
spec.use(myPlugin);With JavaScript:
import spec from "spectrallogs"
const myPlugin = {
name: 'MyCustomPlugin',
init() {
console.log('Plugin initialized');
},
beforeLog(message, level, options) {
return message.toUpperCase();
},
afterLog(message, level, options) {
console.log('Log completed');
},
};
spec.use(myPlugin);Spectral includes a CLI for diagnostics and configuration:
# Show version
npx spec --version
# Show help
npx spec --help
# Show current configuration
npx spec config
# Set configuration
npx spec config set debugMode=true
npx spec config set colors.info=#ff00ff
# Reset configuration
npx spec config reset
# Run performance benchmark
npx spec bench
# Diagnose environment
npx spec doctor
# Open docs in default browser
npx spec docsSpectral automatically formats Error objects with clean stack traces:
try {
throw new Error('Something went wrong');
} catch (error) {
spec.error(error);
}Output includes:
- Error name and message
- Clean, filtered stack trace
- Duplicate error tracking
Spectral is designed for speed. Run the benchmark to see:
npx spec benchTypical results show Spectral is comparable or faster than console.log while providing significantly more features.
In CI, a GitHub Actions workflow runs benchmarks and posts a summary (see .github/workflows/benchmark.yml).
Example output:
console.log: 800ms (12500 logs/sec)
Spectral: 284ms (35200 logs/sec)
Spectral is 64% faster!
spec.log(message, color?, codec?)- Basic logspec.info(message, color?, codec?)- Info levelspec.success(message, color?, codec?)- Success levelspec.warn(message, color?, codec?)- Warning levelspec.error(message, color?, codec?)- Error levelspec.debug(message, color?, codec?)- Debug level (only when debugMode is enabled)
spec.configure(options)- Update configurationspec.use(plugin)- Register a pluginspec.flush()- Force flush buffered outputspec.getConfig()- Get current configurationspec.getErrorStats()- Get error statisticsspec.clearErrorCache()- Clear error cache
Create scoped child loggers that prefix messages, inheriting config and plugins:
import spec from 'spectrallogs';
const api = spec.child('api');
const db = spec.child('db');
api.info('server started'); // => [api] server started
db.warn('slow query'); // => [db] slow queryimport spec from 'spectrallogs';
spec.log('Application started');
spec.info('Loading configuration...');
spec.success('Configuration loaded successfully');const user = { id: 1, name: 'John', active: true };
spec.log(user);spec.configure({
showTimestamp: false,
colors: {
success: '#00ff00',
error: '#ff0000',
},
});import spec, { FileLoggerPlugin, PerformanceTrackerPlugin } from 'spectrallogs';
const fileLogger = new FileLoggerPlugin();
const perfTracker = new PerformanceTrackerPlugin();
spec.use(fileLogger);
spec.use(perfTracker);
spec.info('Logging with multiple plugins');Spectral provides a dedicated web build available under the subpath import spectrallogs/web. This build is optimized for browsers: it uses CSS styling with %c, batching to reduce console overhead, and exposes the same high-level API.
Use the CDN to try Spectral quickly without a bundler:
<script type="module">
import spec from 'https://esm.sh/spectrallogs/web';
spec.success('Hello from Spectral Web via CDN');
spec.info('Colors are applied using CSS styles');
</script>You can also instantiate a logger that writes to the DOM for maximum speed (avoiding DevTools overhead):
<pre id="sink"></pre>
<script type="module">
import { SpectralLoggerWeb } from 'https://esm.sh/spectrallogs/web';
const sinkEl = document.getElementById('sink');
const sink = (args) => { sinkEl.textContent += args.join(' ') + '\n'; };
const logger = new SpectralLoggerWeb({ batching: true, sink });
for (let i = 0; i < 10; i++) logger.info('Fast DOM logging #' + i);
logger.flush();
logger.error(new Error('Example error'));
</script>Install normally and import the web subpath:
npm install spectrallogsIn a Vite/React app:
// src/App.tsx
import { useEffect } from 'react';
import spec, { SpectralLoggerWeb } from 'spectrallogs/web';
export default function App() {
useEffect(() => {
spec.success('Spectral Web ready in React');
// Optional: DOM sink batching
const sink = (args: any[]) => console.log(...args);
const logger = new SpectralLoggerWeb({ batching: true, sink });
logger.info('Batched log via custom sink');
logger.flush();
}, []);
return <div>Open your console to see Spectral logs</div>;
}Notes:
- Use
spectrallogs/webonly in browser contexts. The Node build exports remain underspectrallogs. - The web build uses CSS for colors and supports features like timestamps, levels, and error formatting.
- File-based plugins (e.g.,
FileLogger) are not available in web. Use web-specific plugins/utilities instead.
If working within this repository, you can build the web bundle and import locally:
npm run build:web<script type="module">
import spec from './dist-web/index.js';
spec.info('Loaded from local dist-web');
</script>The Node build (ANSI colors, stdout/stderr buffering) is available at the package root:
import spec from 'spectrallogs';
spec.log('Application started');
spec.info('Loading configuration...');
spec.success('Configuration loaded successfully');CommonJS:
const spec = require('spectrallogs').default;
spec.warn('CJS usage works as well');Spectral automatically detects terminal color support:
- TrueColor (24-bit): Full HEX/RGB support
- 256-color: Approximated colors
- No color: Graceful fallback to plain text
Set COLORTERM=truecolor for best results.
Spectral is written in TypeScript and includes complete type definitions:
import spec, {
SpectralLogger,
SpectralConfigOptions,
Plugin,
LogLevel
} from 'spectrallogs';
const logger = new SpectralLogger();
logger.info('Fully typed');All contributions are welcome. Please note that the main branch is protected — all changes must be made through pull requests.
To contribute:
- Fork the repository and create a feature branch (feat/, fix/, etc.).
- Run checks before submitting:
npm run build- Submit a Pull Request to the main branch. • Direct pushes are not allowed. • All CI checks must pass. • At least one maintainer approval is required before merging.
For detailed contribution guidelines, see the CONTRIBUTING.md file.
MIT
- Fast: Optimized for performance with minimal overhead
- Beautiful: Rich colors and clean formatting out of the box
- Flexible: Powerful plugin system for any use case
- Simple: Drop-in replacement for
console.log - Reliable: Zero dependencies, battle-tested code