debug

repository·master·Indexed 11 days ago

https://github.com/debug-js/debug

A lightweight JavaScript debugging utility for Node.js and the browser (version 4.4.3). It allows developers to toggle debug output for different modules or features using namespaces and environment variables, featuring printf-style formatters and support for wildcards and exclusions.

Tokens
2K
Snippets
9
Records
11
Agent score
45%

What's inside debug

  1. Enable debug in web browsers

    master

    To use debug in a browser, use browserify or a browserify-as-a-service build.

    Debug's enable state is persisted in localStorage. You can enable namespaces manually by setting localStorage.debug and refreshing the page.

    Note for Chromium users: In Chrome, Brave, or Electron, you must set the console log level to 'Verbose' to see debug output.

    // Enable namespaces in the browser console
    localStorage.debug = 'worker:*';
    // Then refresh the page
  2. Basic usage of debug

    master

    The debug module exports a function. When called with a namespace string, it returns a decorated version of console.error that only outputs when that namespace (or a parent/wildcard) is enabled via the DEBUG environment variable.

    To use it, require debug and pass the module or feature name as the namespace.

    var debug = require('debug')('http');
    
    // This will only log if DEBUG=http or DEBUG=* is set
    debug('booting %o', 'My App');
    
    // You can use multiple namespaces
    var a = require('debug')('worker:a');
    var b = require('debug')('worker:b');
    
    a('doing work');
  3. Enable debug namespaces via environment variables

    master

    You can control which debug statements are visible by setting the DEBUG environment variable. Namespaces can be space-delimited or comma-delimited.

    Wildcards and Exclusions

    • Use * as a wildcard to enable everything: DEBUG=*.
    • Use prefix:* to enable all sub-namespaces: DEBUG=connect:*.
    • Use - to exclude specific namespaces: DEBUG=*,-connect:* (enables everything except connect namespaces).

    Platform Specifics

    Windows CMD

    Use the set command:

    set DEBUG=* & node app.js

    Windows PowerShell

    Use the $env: syntax:

    $env:DEBUG='*'; node app.js

    npm scripts

    You can define platform-specific debug commands in your package.json:

    "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js"
    # Example for Unix-like systems
    DEBUG=http,worker:* node app.js
  4. Ensure colors in child processes

    master

    When running child processes in Node.js, debug may not detect a TTY, causing colors to be disabled. To force color output in a child process, set the DEBUG_COLORS=1 environment variable.

    const { fork } = require('child_process');
    
    const worker = fork('worker.js', [], {
      env: Object.assign({}, process.env, {
        DEBUG_COLORS: 1
      }),
    });
    
    worker.stderr.pipe(process.stderr, { end: false });
  5. Redirect debug output to different streams

    master

    By default, debug logs to stderr. You can override the log method for a specific namespace or globally to redirect output to stdout or other streams.

    var debug = require('debug');
    
    // Redirect a specific namespace to stdout
    var log = debug('app:log');
    log.log = console.log.bind(console);
    log('this goes to stdout');
    
    // Redirect ALL debug output to console.info
    debug.log = console.info.bind(console);
  6. Extend and dynamically manage debug instances

    master

    Extending Namespaces

    You can create new debug instances with extended namespaces using the .extend() method:

    const log = require('debug')('auth');
    const logSign = log.extend('sign'); // namespace becomes 'auth:sign'
    logSign('hello');

    Dynamic Control

    You can enable or disable namespaces programmatically using debug.enable() and debug.disable().

    • debug.enable(namespaces): Enables specific namespaces. Note: This completely overrides any previously set DEBUG environment variable.
    • debug.disable(): Disables all namespaces and returns the list of namespaces that were previously enabled (so you can restore them later).
    • debug.enabled(namespace): Returns a boolean indicating if a specific namespace is currently active.
    • instance.enabled: A property on a debug instance that returns whether that specific instance is active.
    let debug = require('debug');
    
    // Check if enabled
    console.log(debug.enabled('test')); // false
    
    // Enable dynamically
    debug.enable('test');
    console.log(debug.enabled('test')); // true
    
    // Disable all and capture state
    let namespaces = debug.disable();
    
    // Restore previous state
    debug.enable(namespaces);
  7. Add custom formatters to debug

    master

    You can extend the debug.formatters object to add support for custom data types. For example, to add a %h formatter that renders a Buffer as hex:

    const createDebug = require('debug');
    
    // Define the custom formatter
    createDebug.formatters.h = (v) => {
      return v.toString('hex');
    };
    
    const debug = createDebug('foo');
    // Usage: 'foo this is hex: 68656c6c6f20776f726c6421 +0ms'
    debug('this is hex: %h', Buffer.from('hello world'));
  8. Use printf-style formatters in debug

    master

    The debug utility supports printf-style formatting. Supported formatters include:

    FormatterRepresentation
    %OPretty-print an Object on multiple lines.
    %oPretty-print an Object all on a single line.
    %sString.
    %dNumber (both integer and float).
    %jJSON. Replaced with the string '[Circular]' if the argument contains circular references.
    %%Single percent sign ('%'). Does not consume an argument.
  9. Configure debug behavior with environment variables

    master

    When running in Node.js, you can use several environment variables to modify the output behavior. Variables starting with DEBUG_ are passed as options to the %o/%O formatters (similar to util.inspect() options).

    NamePurpose
    DEBUGEnables/disables specific debugging namespaces.
    DEBUG_HIDE_DATEHide date from debug output (non-TTY).
    DEBUG_COLORSWhether or not to use colors in the debug output.
    DEBUG_DEPTHObject inspection depth.
    DEBUG_SHOW_HIDDENShows hidden properties on inspected objects.
  10. Initialize debug for Node.js or Browser environments

    master

    The debug package automatically detects your runtime environment. It exports a function that works in Node.js and browser environments (including Electron renderer processes and NW.js).

    • In Node.js, it uses standard output streams.
    • In Browsers (or Electron/NW.js), it uses console.log.

    To use it, simply require or import the package. The environment detection logic checks for the presence of process and specific flags like process.type === 'renderer', process.browser === true, or process.__nwjs to decide whether to load the browser-compatible implementation.

    const debug = require('debug');
    const log = debug('app:module');
    
    log('Hello world!');