New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

debug-better

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

debug-better

Advanced TypeScript debugging utility with filtering capabilities for Node.js and browser

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

debug-better

npm version TypeScript Node.js

A modern, TypeScript-based debugging utility with advanced filtering capabilities for Node.js and browser environments. Built as an enhanced version of the popular debug package with additional features.

Features

  • TypeScript Support - Full TypeScript types and definitions
  • 🎯 Advanced Filtering - Regex patterns, predicates, and custom filters
  • 🎨 Colorized Output - Beautiful colored output in terminal and browser console
  • 🌐 Universal - Works in Node.js and browser environments
  • Performance - Lightweight with minimal overhead
  • 📊 Metadata Support - Attach contextual data to log instances
  • 🔧 Extensible - Easy to extend and customize

Installation

npm install debug-better

Quick Start

Basic Usage

import debug from 'debug-better';

const log = debug('app:server');

log('Server starting on port %d', 3000);
log('Connected to database');

Enable Debug Output

Node.js:

DEBUG=* node app.js              # Enable all
DEBUG=app:* node app.js          # Enable app namespace
DEBUG=app:*,-app:verbose node app.js  # Enable app except verbose

Browser:

localStorage.setItem('debug', 'app:*');
// Or via URL: ?debug=app:*

Advanced Features

1. TypeScript Support

Full type safety and IntelliSense:

import debug, { Debugger, FilterOptions } from 'debug-better';

const log: Debugger = debug('my-app');

const filterOpts: FilterOptions = {
  enabled: true,
  patterns: [/^api:.*/],
  exclude: ['api:debug'],
};

2. Advanced Filtering

Pattern-Based Filtering

import debug from 'debug-better';

// Set global filter
debug.setGlobalFilter({
  include: ['app:*', 'api:*'],
  exclude: ['*:verbose', '*:debug'],
});

const log = debug('app:main');
log('This will be shown');

const verboseLog = debug('app:verbose');
verboseLog('This will be hidden');

Regex Filtering

import debug from 'debug-better';

debug.setGlobalFilter({
  patterns: [
    /^api:.*$/,        // Match all api namespaces
    /^app:(server|db)$/,  // Match specific namespaces
  ],
});

Custom Predicate Filters

import debug from 'debug-better';

debug.setGlobalFilter({
  predicates: [
    // Only log during business hours
    (namespace: string) => {
      const hour = new Date().getHours();
      return hour >= 9 && hour <= 17;
    },
    // Only log errors and warnings
    (namespace: string, ...args: any[]) => {
      const msg = args[0]?.toString() || '';
      return msg.includes('error') || msg.includes('warning');
    },
  ],
});

Instance-Specific Filtering

import debug from 'debug-better';

const log = debug('app:main', {
  filter: {
    enabled: true,
    predicates: [
      (namespace, ...args) => {
        // Custom logic for this instance
        return args[0]?.priority === 'high';
      },
    ],
  },
});

log({ priority: 'high' }, 'Important message');  // Shown
log({ priority: 'low' }, 'Regular message');     // Hidden

3. Metadata Support

Attach contextual data to debugger instances:

import debug from 'debug-better';

const log = debug('api:user', {
  metadata: {
    service: 'user-service',
    version: '1.0.0',
  },
});

log.setMetadata('requestId', '12345');
log('Processing request');

console.log(log.getMetadata('service')); // 'user-service'

4. Custom Formatters

import debug from 'debug-better';

// Add custom formatter
debug.formatters.j = (v: any) => {
  return JSON.stringify(v, null, 2);
};

const log = debug('app');
log('Config: %j', { port: 3000, host: 'localhost' });

5. Extending Debuggers

Create sub-namespaces:

import debug from 'debug-better';

const app = debug('app');
const server = app.extend('server');
const db = app.extend('db');

app('Application started');      // app
server('Server listening');      // app:server
db('Connected to database');     // app:db

6. Custom Options

import debug from 'debug-better';

const log = debug('app', {
  useColors: true,
  hideDate: false,
  metadata: { environment: 'production' },
  log: (...args) => {
    // Custom log function
    console.log('[CUSTOM]', ...args);
  },
});

API Reference

Factory Function

debug(namespace: string, options?: DebugOptions): Debugger

Options

  • namespace: String identifier for the debugger instance
  • useColors: Enable/disable colors (default: auto-detected)
  • hideDate: Hide timestamp in output
  • log: Custom log function
  • filter: Instance-specific filter options
  • metadata: Additional contextual data

Debugger Instance

Methods

  • log(...args): Log a message
  • extend(namespace, delimiter?): Create a sub-debugger
  • setFilter(filter): Update filter options
  • setMetadata(key, value): Set metadata
  • getMetadata(key): Get metadata

Properties

  • namespace: The namespace string
  • enabled: Whether this debugger is enabled
  • useColors: Whether colors are used
  • color: Assigned color
  • diff: Time difference from previous log

Global Methods

debug.enable(namespaces: string): void
debug.disable(): string
debug.enabled(name: string): boolean
debug.setGlobalFilter(filter: FilterOptions): void
debug.getGlobalFilter(): FilterOptions

Filter Options

interface FilterOptions {
  enabled?: boolean;
  patterns?: RegExp[];
  predicates?: FilterPredicate[];
  include?: string[];
  exclude?: string[];
  tags?: string[];
  minLevel?: number;
  maxLevel?: number;
}

Environment Variables (Node.js)

  • DEBUG: Enable namespaces (e.g., DEBUG=app:*)
  • DEBUG_COLORS: Force colors on/off
  • DEBUG_HIDE_DATE: Hide timestamps
  • DEBUG_SHOW_HIDDEN: Show hidden properties in objects

Browser Console

In browser environments, you can:

  • Set via localStorage: localStorage.setItem('debug', 'app:*')
  • Set via URL parameter: ?debug=app:*
  • Use browser console: debug.enable('app:*')

Examples

Express Server

import debug from 'debug-better';
import express from 'express';

const app = express();
const log = debug('server');
const reqLog = debug('server:request');
const errLog = debug('server:error');

app.use((req, res, next) => {
  reqLog('%s %s', req.method, req.url);
  next();
});

app.get('/', (req, res) => {
  log('Handling root request');
  res.send('Hello World');
});

app.use((err, req, res, next) => {
  errLog('Error: %O', err);
  res.status(500).send('Internal Server Error');
});

const PORT = 3000;
app.listen(PORT, () => {
  log('Server started on port %d', PORT);
});

Microservice with Filtering

import debug from 'debug-better';

// Only log errors and warnings in production
if (process.env.NODE_ENV === 'production') {
  debug.setGlobalFilter({
    predicates: [
      (namespace, ...args) => {
        const msg = JSON.stringify(args);
        return msg.includes('error') || msg.includes('warn');
      },
    ],
  });
}

const log = debug('service:main');
const errorLog = debug('service:error');

log('Service starting...'); // Hidden in production
errorLog('Critical error occurred!'); // Always shown

Migration from debug

debug-better is designed to be a drop-in replacement for the debug package:

// Before
const debug = require('debug');
const log = debug('app');

// After
import debug from 'debug-better';
const log = debug('app');

All existing functionality is preserved, with additional features available when needed.

Performance

debug-better is designed with performance in mind:

  • Disabled debuggers have near-zero overhead
  • Filtering is evaluated lazily
  • No dependencies beyond ms for time formatting

Browser Support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Edge (latest)
  • IE11+ (with polyfills)

Node.js Support

  • Node.js >= 18.0.0 (LTS)

License

MIT © Your Name

Contributing

Contributions are welcome! Please read our contributing guidelines and code of conduct.

Credits

Inspired by the excellent debug package by TJ Holowaychuk and contributors.

Changelog

1.0.0

  • Initial release
  • TypeScript support
  • Advanced filtering capabilities
  • Metadata support
  • Full backward compatibility with debug

Keywords

debug

FAQs

Package last updated on 06 Dec 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts