Skip to content

substrate-system/debug

Repository files navigation

debug

tests module types semantic versioning install size GZip size license

A tiny JavaScript debugging utility that works in Node.js and browsers. Use environment variables to control logging in Node.js, and localStorage to control logging in browsers, so there are no ridiculous console log statements in production.

This is based on debug. It's been rewritten to use contemporary JS.

In the browser, this uses localStorage to control debug output. In Node.js, it uses the environment variable DEBUG.

Featuring:

  • Use exports field in package.json to choose node JS or browser version
  • ESM only

Plus, see the docs generated by typescript.

Contents

Install

npm i -D @substrate-system/debug

Browser usage: Use localStorage DEBUG key. Node.js usage: Use environment variable DEBUG.

Browser

In the browser, this looks for the DEBUG key in localStorage.

import Debug from '@substrate-system/debug'

// Set DEBUG in localStorage
localStorage.setItem('DEBUG', 'myapp:*')

const debug = Debug('myapp:component')
debug('hello logs')
// will log, because DEBUG in localStorage matches 'myapp:*'

Node JS

Run your script with an env variable, DEBUG.

// in node JS
import createDebug from '@substrate-system/debug/node'
const debug = createDebug('fooo')
debug('testing')

Call this with an env var of DEBUG=fooo

DEBUG=fooo node ./test/fixture/node.js

Config

Namespace

In browsers, this checks localStorage for DEBUG key. In Node.js, this checks the environment variable DEBUG.

import Debug from '@substrate-system/debug'

// In browser: checks localStorage.getItem('DEBUG')
const debug = Debug('example')

// Log if no namespace is set in localStorage
const debug = Debug(import.meta.env.DEV)

Enable all namespaces

localStorage.setItem('DEBUG', '*')

Enable specific namespaces

localStorage.setItem('DEBUG', 'myapp:auth,myapp:api')

Force logging with boolean true

You can also pass true to force logging regardless of localStorage. For example, in Vite, this will log on your localhost server, but not in production:

const debug = Debug(import.meta.env.DEV)
debug('This logs')

Develop

browser

Start a vite server and log some things. This uses the example directory.

npm start

Test

Node

Run tests:

npm test

Contributors 3

  •  
  •  
  •