Debug

A tiny JavaScript debugging utility modelled after Node.js core's debugging...

README

debug Build Status  Coverage Status  Slack OpenCollective OpenCollective



A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.

Installation


  1. ``` sh
  2. $ npm install debug
  3. ```

Usage


debug exposes a function; simply pass this function the name of your module, and it will return a decorated version of console.error for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.

Example _app.js_:

  1. ``` js
  2. var debug = require('debug')('http')
  3.   , http = require('http')
  4.   , name = 'My App';

  5. // fake app

  6. debug('booting %o', name);

  7. http.createServer(function(req, res){
  8.   debug(req.method + ' ' + req.url);
  9.   res.end('hello\n');
  10. }).listen(3000, function(){
  11.   debug('listening');
  12. });

  13. // fake worker of some kind

  14. require('./worker');
  15. ```

Example _worker.js_:

  1. ``` js
  2. var a = require('debug')('worker:a')
  3.   , b = require('debug')('worker:b');

  4. function work() {
  5.   a('doing lots of uninteresting work');
  6.   setTimeout(work, Math.random() * 1000);
  7. }

  8. work();

  9. function workb() {
  10.   b('doing some work');
  11.   setTimeout(workb, Math.random() * 2000);
  12. }

  13. workb();
  14. ```

The DEBUG environment variable is then used to enable these based on space or
comma-delimited names.

Here are some examples:

screen shot 2017-08-08 at 12 53 04 pmscreen shot 2017-08-08 at 12 53 38 pmscreen shot 2017-08-08 at 12 53 25 pm

Windows command prompt notes


CMD

On Windows the environment variable is set using the set command.

  1. ```cmd
  2. set DEBUG=*,-not_this
  3. ```

Example:

  1. ```cmd
  2. set DEBUG=* & node app.js
  3. ```

PowerShell (VS Code default)

PowerShell uses different syntax to set environment variables.

  1. ```cmd
  2. $env:DEBUG = "*,-not_this"
  3. ```

Example:

  1. ```cmd
  2. $env:DEBUG='app';node app.js
  3. ```

Then, run the program to be debugged as usual.

npm script example:
  1. ``` js
  2.   "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
  3. ```

Namespace Colors


Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.

Node.js


In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [supports-color](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.


Web Browser


Colors are also enabled on "Web Inspectors" that understand the %c formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).



Millisecond diff


When actively developing an application it can be useful to see when the time spent between one debug() call and the next. Suppose for example you invoke debug() before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.


When stdout is not a TTY, Date#toISOString() is used, making it more useful for logging the debug information as shown below:



Conventions


If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".  If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable.  You can then use it for normal output as well as debug output.

Wildcards


The * character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
DEBUG=connect:bodyParser,connect:compress,connect:session, you may simply do
`DEBUG=connect:, or to run everything using this module simply use DEBUG=`.

You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=,-connect:` would include all debuggers except those
starting with "connect:".

Environment Variables


When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:

NamePurpose
|-----------|-------------------------------------------------|
`DEBUG`Enables/disables
`DEBUG_HIDE_DATE`Hide
`DEBUG_COLORS`|
`DEBUG_DEPTH`Object
`DEBUG_SHOW_HIDDEN`Shows


__Note:__ The environment variables beginning with DEBUG_ end up being
converted into an Options object that gets used with %o/%O formatters.
See the Node.js documentation for
[util.inspect()](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.

Formatters


Debug uses printf-style formatting.
Below are the officially supported formatters:

FormatterRepresentation
|-----------|----------------|
`%O`Pretty-print
`%o`Pretty-print
`%s`String.
`%d`Number
`%j`JSON.
`%%`Single


Custom formatters


You can add custom formatters by extending the debug.formatters object.
For example, if you wanted to add support for rendering a Buffer as hex with
%h, you could do something like:

  1. ``` js
  2. const createDebug = require('debug')
  3. createDebug.formatters.h = (v) => {
  4.   return v.toString('hex')
  5. }

  6. // …elsewhere
  7. const debug = createDebug('foo')
  8. debug('this is hex: %h', new Buffer('hello world'))
  9. //   foo this is hex: 68656c6c6f20776f726c6421 +0ms
  10. ```


Browser Support


You can build a browser-ready script using browserify,
if you don't want to build it yourself.

Debug's enable state is currently persisted by localStorage.
Consider the situation shown below where you have worker:a and worker:b,
and wish to debug both. You can enable this using localStorage.debug:

  1. ``` js
  2. localStorage.debug = 'worker:*'
  3. ```

And then refresh the page.

  1. ``` js
  2. a = debug('worker:a');
  3. b = debug('worker:b');

  4. setInterval(function(){
  5.   a('doing some work');
  6. }, 1000);

  7. setInterval(function(){
  8.   b('doing some work');
  9. }, 1200);
  10. ```

In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by debug if the "Verbose" log level is _enabled_.


Output streams


  By default debug will log to stderr, however this can be configured per-namespace by overriding the log method:

Example _stdout.js_:

  1. ``` js
  2. var debug = require('debug');
  3. var error = debug('app:error');

  4. // by default stderr is used
  5. error('goes to stderr!');

  6. var log = debug('app:log');
  7. // set this namespace to log via console.log
  8. log.log = console.log.bind(console); // don't forget to bind to console!
  9. log('goes to stdout');
  10. error('still goes to stderr!');

  11. // set all output to go via console.info
  12. // overrides all per-namespace log settings
  13. debug.log = console.info.bind(console);
  14. error('now goes to stdout via console.info');
  15. log('still goes to stdout, but via console.info now');
  16. ```

Extend

You can simply extend debugger
  1. ``` js
  2. const log = require('debug')('auth');

  3. //creates new debug instance with extended namespace
  4. const logSign = log.extend('sign');
  5. const logLogin = log.extend('login');

  6. log('hello'); // auth hello
  7. logSign('hello'); //auth:sign hello
  8. logLogin('hello'); //auth:login hello
  9. ```

Set dynamically


You can also enable debug dynamically by calling the enable() method :

  1. ``` js
  2. let debug = require('debug');

  3. console.log(1, debug.enabled('test'));

  4. debug.enable('test');
  5. console.log(2, debug.enabled('test'));

  6. debug.disable();
  7. console.log(3, debug.enabled('test'));

  8. ```

print :  
  1. ```
  2. 1 false
  3. 2 true
  4. 3 false
  5. ```

Usage :  
enable(namespaces)  
namespaces can include modes separated by a colon and wildcards.
  
Note that calling enable() completely overrides previously set DEBUG variable :

  1. ```
  2. $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
  3. => false
  4. ```

disable()

Will disable all namespaces. The functions returns the namespaces currently
enabled (and skipped). This can be useful if you want to disable debugging
temporarily without knowing what was enabled to begin with.

For example:

  1. ``` js
  2. let debug = require('debug');
  3. debug.enable('foo:*,-foo:bar');
  4. let namespaces = debug.disable();
  5. debug.enable(namespaces);
  6. ```

Note: There is no guarantee that the string will be identical to the initial
enable string, but semantically they will be identical.

Checking whether a debug target is enabled


After you've created a debug instance, you can determine whether or not it is
enabled by checking the enabled property:

  1. ``` js
  2. const debug = require('debug')('http');

  3. if (debug.enabled) {
  4.   // do stuff...
  5. }
  6. ```

You can also manually toggle this property to force the debug instance to be
enabled or disabled.

Usage in child processes


Due to the way debug detects if the output is a TTY or not, colors are not shown in child processes when stderr is piped. A solution is to pass the DEBUG_COLORS=1 environment variable to the child process.  
For example:

  1. ``` js
  2. worker = fork(WORKER_WRAP_PATH, [workerPath], {
  3.   stdio: [
  4.     /* stdin: */ 0,
  5.     /* stdout: */ 'pipe',
  6.     /* stderr: */ 'pipe',
  7.     'ipc',
  8.   ],
  9.   env: Object.assign({}, process.env, {
  10.     DEBUG_COLORS: 1 // without this settings, colors won't be shown
  11.   }),
  12. });

  13. worker.stderr.pipe(process.stderr, { end: false });
  14. ```


Authors


- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
- Josh Junon

Backers


Support us with a monthly donation and help us continue our activities. [Become a backer]



Sponsors


Become a sponsor and get your logo on our README on Github with a link to your site. [Become a sponsor]


License


(The MIT License)

Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2018-2021 Josh Junon

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.