├── .editorconfig ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── karma.conf.js ├── package.json ├── src ├── browser.js ├── common.js ├── index.js └── node.js ├── test.js └── test.node.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | indent_size = 4 6 | tab_width = 4 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [{*.json,*.json.example,*.gyp,*.yml,*.yaml}] 13 | indent_style = space 14 | indent_size = 2 15 | 16 | [{*.py,*.asm}] 17 | indent_style = space 18 | 19 | [*.py] 20 | indent_size = 4 21 | 22 | [*.asm] 23 | indent_size = 8 24 | 25 | [*.md] 26 | trim_trailing_whitespace = false 27 | 28 | # Ideal settings - some plugins might support these. 29 | [*.js] 30 | quote_type = single 31 | 32 | [{*.c,*.cc,*.h,*.hh,*.cpp,*.hpp,*.m,*.mm,*.mpp,*.js,*.java,*.go,*.rs,*.php,*.ng,*.jsx,*.ts,*.d,*.cs,*.swift}] 33 | curly_bracket_next_line = false 34 | spaces_around_operators = true 35 | spaces_around_brackets = outside 36 | # close enough to 1TB 37 | indent_brace_style = K&R 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | *.sock 4 | /build/ 5 | npm-debug.log 6 | yarn-error.log 7 | /dist/ 8 | /coverage/ 9 | 10 | # lockfiles 11 | yarn.lock 12 | package-lock.json 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: node_js 4 | 5 | node_js: 6 | - "6" 7 | - "8" 8 | - "10" 9 | - "11" 10 | 11 | install: 12 | - npm install 13 | 14 | script: 15 | - npm run lint 16 | - npm test 17 | - npm run test:coverage 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | (The MIT License) 2 | 3 | Copyright (c) 2014-2017 TJ Holowaychuk 4 | Copyright (c) 2018-2021 Josh Junon 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software 7 | and associated documentation files (the 'Software'), to deal in the Software without restriction, 8 | including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 | and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all copies or substantial 13 | portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 16 | LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 17 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 18 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 19 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 20 | 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # debug 2 | [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) 3 | [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) 4 | 5 | 6 | 7 | A tiny JavaScript debugging utility modelled after Node.js core's debugging 8 | technique. Works in Node.js and web browsers. 9 | 10 | ## Installation 11 | 12 | ```bash 13 | $ npm install debug 14 | ``` 15 | 16 | ## Usage 17 | 18 | `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. 19 | 20 | Example [_app.js_](./examples/node/app.js): 21 | 22 | ```js 23 | var debug = require('debug')('http') 24 | , http = require('http') 25 | , name = 'My App'; 26 | 27 | // fake app 28 | 29 | debug('booting %o', name); 30 | 31 | http.createServer(function(req, res){ 32 | debug(req.method + ' ' + req.url); 33 | res.end('hello\n'); 34 | }).listen(3000, function(){ 35 | debug('listening'); 36 | }); 37 | 38 | // fake worker of some kind 39 | 40 | require('./worker'); 41 | ``` 42 | 43 | Example [_worker.js_](./examples/node/worker.js): 44 | 45 | ```js 46 | var a = require('debug')('worker:a') 47 | , b = require('debug')('worker:b'); 48 | 49 | function work() { 50 | a('doing lots of uninteresting work'); 51 | setTimeout(work, Math.random() * 1000); 52 | } 53 | 54 | work(); 55 | 56 | function workb() { 57 | b('doing some work'); 58 | setTimeout(workb, Math.random() * 2000); 59 | } 60 | 61 | workb(); 62 | ``` 63 | 64 | The `DEBUG` environment variable is then used to enable these based on space or 65 | comma-delimited names. 66 | 67 | Here are some examples: 68 | 69 | screen shot 2017-08-08 at 12 53 04 pm 70 | screen shot 2017-08-08 at 12 53 38 pm 71 | screen shot 2017-08-08 at 12 53 25 pm 72 | 73 | #### Windows command prompt notes 74 | 75 | ##### CMD 76 | 77 | On Windows the environment variable is set using the `set` command. 78 | 79 | ```cmd 80 | set DEBUG=*,-not_this 81 | ``` 82 | 83 | Example: 84 | 85 | ```cmd 86 | set DEBUG=* & node app.js 87 | ``` 88 | 89 | ##### PowerShell (VS Code default) 90 | 91 | PowerShell uses different syntax to set environment variables. 92 | 93 | ```cmd 94 | $env:DEBUG = "*,-not_this" 95 | ``` 96 | 97 | Example: 98 | 99 | ```cmd 100 | $env:DEBUG='app';node app.js 101 | ``` 102 | 103 | Then, run the program to be debugged as usual. 104 | 105 | npm script example: 106 | ```js 107 | "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", 108 | ``` 109 | 110 | ## Namespace Colors 111 | 112 | Every debug instance has a color generated for it based on its namespace name. 113 | This helps when visually parsing the debug output to identify which debug instance 114 | a debug line belongs to. 115 | 116 | #### Node.js 117 | 118 | In Node.js, colors are enabled when stderr is a TTY. You also _should_ install 119 | the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, 120 | otherwise debug will only use a small handful of basic colors. 121 | 122 | 123 | 124 | #### Web Browser 125 | 126 | Colors are also enabled on "Web Inspectors" that understand the `%c` formatting 127 | option. These are WebKit web inspectors, Firefox ([since version 128 | 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) 129 | and the Firebug plugin for Firefox (any version). 130 | 131 | 132 | 133 | 134 | ## Millisecond diff 135 | 136 | 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. 137 | 138 | 139 | 140 | When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: 141 | 142 | 143 | 144 | 145 | ## Conventions 146 | 147 | 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. 148 | 149 | ## Wildcards 150 | 151 | The `*` character may be used as a wildcard. Suppose for example your library has 152 | debuggers named "connect:bodyParser", "connect:compress", "connect:session", 153 | instead of listing all three with 154 | `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do 155 | `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. 156 | 157 | You can also exclude specific debuggers by prefixing them with a "-" character. 158 | For example, `DEBUG=*,-connect:*` would include all debuggers except those 159 | starting with "connect:". 160 | 161 | ## Environment Variables 162 | 163 | When running through Node.js, you can set a few environment variables that will 164 | change the behavior of the debug logging: 165 | 166 | | Name | Purpose | 167 | |-----------|-------------------------------------------------| 168 | | `DEBUG` | Enables/disables specific debugging namespaces. | 169 | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | 170 | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | 171 | | `DEBUG_DEPTH` | Object inspection depth. | 172 | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | 173 | 174 | 175 | __Note:__ The environment variables beginning with `DEBUG_` end up being 176 | converted into an Options object that gets used with `%o`/`%O` formatters. 177 | See the Node.js documentation for 178 | [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) 179 | for the complete list. 180 | 181 | ## Formatters 182 | 183 | Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. 184 | Below are the officially supported formatters: 185 | 186 | | Formatter | Representation | 187 | |-----------|----------------| 188 | | `%O` | Pretty-print an Object on multiple lines. | 189 | | `%o` | Pretty-print an Object all on a single line. | 190 | | `%s` | String. | 191 | | `%d` | Number (both integer and float). | 192 | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | 193 | | `%%` | Single percent sign ('%'). This does not consume an argument. | 194 | 195 | 196 | ### Custom formatters 197 | 198 | You can add custom formatters by extending the `debug.formatters` object. 199 | For example, if you wanted to add support for rendering a Buffer as hex with 200 | `%h`, you could do something like: 201 | 202 | ```js 203 | const createDebug = require('debug') 204 | createDebug.formatters.h = (v) => { 205 | return v.toString('hex') 206 | } 207 | 208 | // …elsewhere 209 | const debug = createDebug('foo') 210 | debug('this is hex: %h', new Buffer('hello world')) 211 | // foo this is hex: 68656c6c6f20776f726c6421 +0ms 212 | ``` 213 | 214 | 215 | ## Browser Support 216 | 217 | You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), 218 | or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), 219 | if you don't want to build it yourself. 220 | 221 | Debug's enable state is currently persisted by `localStorage`. 222 | Consider the situation shown below where you have `worker:a` and `worker:b`, 223 | and wish to debug both. You can enable this using `localStorage.debug`: 224 | 225 | ```js 226 | localStorage.debug = 'worker:*' 227 | ``` 228 | 229 | And then refresh the page. 230 | 231 | ```js 232 | a = debug('worker:a'); 233 | b = debug('worker:b'); 234 | 235 | setInterval(function(){ 236 | a('doing some work'); 237 | }, 1000); 238 | 239 | setInterval(function(){ 240 | b('doing some work'); 241 | }, 1200); 242 | ``` 243 | 244 | 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_. 245 | 246 | 247 | 248 | ## Output streams 249 | 250 | By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: 251 | 252 | Example [_stdout.js_](./examples/node/stdout.js): 253 | 254 | ```js 255 | var debug = require('debug'); 256 | var error = debug('app:error'); 257 | 258 | // by default stderr is used 259 | error('goes to stderr!'); 260 | 261 | var log = debug('app:log'); 262 | // set this namespace to log via console.log 263 | log.log = console.log.bind(console); // don't forget to bind to console! 264 | log('goes to stdout'); 265 | error('still goes to stderr!'); 266 | 267 | // set all output to go via console.info 268 | // overrides all per-namespace log settings 269 | debug.log = console.info.bind(console); 270 | error('now goes to stdout via console.info'); 271 | log('still goes to stdout, but via console.info now'); 272 | ``` 273 | 274 | ## Extend 275 | You can simply extend debugger 276 | ```js 277 | const log = require('debug')('auth'); 278 | 279 | //creates new debug instance with extended namespace 280 | const logSign = log.extend('sign'); 281 | const logLogin = log.extend('login'); 282 | 283 | log('hello'); // auth hello 284 | logSign('hello'); //auth:sign hello 285 | logLogin('hello'); //auth:login hello 286 | ``` 287 | 288 | ## Set dynamically 289 | 290 | You can also enable debug dynamically by calling the `enable()` method : 291 | 292 | ```js 293 | let debug = require('debug'); 294 | 295 | console.log(1, debug.enabled('test')); 296 | 297 | debug.enable('test'); 298 | console.log(2, debug.enabled('test')); 299 | 300 | debug.disable(); 301 | console.log(3, debug.enabled('test')); 302 | 303 | ``` 304 | 305 | print : 306 | ``` 307 | 1 false 308 | 2 true 309 | 3 false 310 | ``` 311 | 312 | Usage : 313 | `enable(namespaces)` 314 | `namespaces` can include modes separated by a colon and wildcards. 315 | 316 | Note that calling `enable()` completely overrides previously set DEBUG variable : 317 | 318 | ``` 319 | $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' 320 | => false 321 | ``` 322 | 323 | `disable()` 324 | 325 | Will disable all namespaces. The functions returns the namespaces currently 326 | enabled (and skipped). This can be useful if you want to disable debugging 327 | temporarily without knowing what was enabled to begin with. 328 | 329 | For example: 330 | 331 | ```js 332 | let debug = require('debug'); 333 | debug.enable('foo:*,-foo:bar'); 334 | let namespaces = debug.disable(); 335 | debug.enable(namespaces); 336 | ``` 337 | 338 | Note: There is no guarantee that the string will be identical to the initial 339 | enable string, but semantically they will be identical. 340 | 341 | ## Checking whether a debug target is enabled 342 | 343 | After you've created a debug instance, you can determine whether or not it is 344 | enabled by checking the `enabled` property: 345 | 346 | ```javascript 347 | const debug = require('debug')('http'); 348 | 349 | if (debug.enabled) { 350 | // do stuff... 351 | } 352 | ``` 353 | 354 | You can also manually toggle this property to force the debug instance to be 355 | enabled or disabled. 356 | 357 | ## Usage in child processes 358 | 359 | 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. 360 | For example: 361 | 362 | ```javascript 363 | worker = fork(WORKER_WRAP_PATH, [workerPath], { 364 | stdio: [ 365 | /* stdin: */ 0, 366 | /* stdout: */ 'pipe', 367 | /* stderr: */ 'pipe', 368 | 'ipc', 369 | ], 370 | env: Object.assign({}, process.env, { 371 | DEBUG_COLORS: 1 // without this settings, colors won't be shown 372 | }), 373 | }); 374 | 375 | worker.stderr.pipe(process.stderr, { end: false }); 376 | ``` 377 | 378 | 379 | ## Authors 380 | 381 | - TJ Holowaychuk 382 | - Nathan Rajlich 383 | - Andrew Rhyne 384 | - Josh Junon 385 | 386 | ## Backers 387 | 388 | Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | ## Sponsors 423 | 424 | Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | ## License 458 | 459 | (The MIT License) 460 | 461 | Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> 462 | Copyright (c) 2018-2021 Josh Junon 463 | 464 | Permission is hereby granted, free of charge, to any person obtaining 465 | a copy of this software and associated documentation files (the 466 | 'Software'), to deal in the Software without restriction, including 467 | without limitation the rights to use, copy, modify, merge, publish, 468 | distribute, sublicense, and/or sell copies of the Software, and to 469 | permit persons to whom the Software is furnished to do so, subject to 470 | the following conditions: 471 | 472 | The above copyright notice and this permission notice shall be 473 | included in all copies or substantial portions of the Software. 474 | 475 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 476 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 477 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 478 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 479 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 480 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 481 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 482 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | module.exports = function (config) { 2 | config.set({ 3 | // Frameworks to use 4 | // available frameworks: https://npmjs.org/browse/keyword/karma-adapter 5 | frameworks: ['browserify', 'mocha'], 6 | 7 | // List of files / patterns to load in the browser 8 | files: [ 9 | 'src/browser.js', 10 | 'src/common.js', 11 | 'test.js' 12 | ], 13 | 14 | // Test results reporter to use 15 | // possible values: 'dots', 'progress' 16 | // available reporters: https://npmjs.org/browse/keyword/karma-reporter 17 | reporters: ['progress'], 18 | 19 | // Web server port 20 | port: 9876, 21 | 22 | // Enable / disable colors in the output (reporters and logs) 23 | colors: true, 24 | 25 | // Level of logging 26 | // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG 27 | logLevel: config.LOG_DEBUG, 28 | 29 | // Start these browsers 30 | // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher 31 | browsers: ['HeadlessChrome'], 32 | customLaunchers: { 33 | HeadlessChrome: { 34 | base: 'ChromeHeadless', 35 | flags: ['--no-sandbox'] 36 | } 37 | }, 38 | 39 | preprocessors: { 40 | // *Sigh* what a glob, folks! 41 | '{{!(node_modules),*.js},!(node_modules)/**/*.js}': ['browserify'] 42 | }, 43 | 44 | browserify: { 45 | debug: true, 46 | transform: ['brfs'] 47 | }, 48 | 49 | // Continuous Integration mode 50 | // if true, Karma captures browsers, runs the tests and exits 51 | singleRun: true, 52 | 53 | // Concurrency level 54 | // how many browser should be started simultaneous 55 | concurrency: 1 56 | }); 57 | }; 58 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "debug", 3 | "version": "4.4.1", 4 | "repository": { 5 | "type": "git", 6 | "url": "git://github.com/debug-js/debug.git" 7 | }, 8 | "description": "Lightweight debugging utility for Node.js and the browser", 9 | "keywords": [ 10 | "debug", 11 | "log", 12 | "debugger" 13 | ], 14 | "files": [ 15 | "src", 16 | "LICENSE", 17 | "README.md" 18 | ], 19 | "author": "Josh Junon (https://github.com/qix-)", 20 | "contributors": [ 21 | "TJ Holowaychuk ", 22 | "Nathan Rajlich (http://n8.io)", 23 | "Andrew Rhyne " 24 | ], 25 | "license": "MIT", 26 | "scripts": { 27 | "lint": "xo", 28 | "test": "npm run test:node && npm run test:browser && npm run lint", 29 | "test:node": "mocha test.js test.node.js", 30 | "test:browser": "karma start --single-run", 31 | "test:coverage": "cat ./coverage/lcov.info | coveralls" 32 | }, 33 | "dependencies": { 34 | "ms": "^2.1.3" 35 | }, 36 | "devDependencies": { 37 | "brfs": "^2.0.1", 38 | "browserify": "^16.2.3", 39 | "coveralls": "^3.0.2", 40 | "karma": "^3.1.4", 41 | "karma-browserify": "^6.0.0", 42 | "karma-chrome-launcher": "^2.2.0", 43 | "karma-mocha": "^1.3.0", 44 | "mocha": "^5.2.0", 45 | "mocha-lcov-reporter": "^1.2.0", 46 | "sinon": "^14.0.0", 47 | "xo": "^0.23.0" 48 | }, 49 | "peerDependenciesMeta": { 50 | "supports-color": { 51 | "optional": true 52 | } 53 | }, 54 | "main": "./src/index.js", 55 | "browser": "./src/browser.js", 56 | "engines": { 57 | "node": ">=6.0" 58 | }, 59 | "xo": { 60 | "rules": { 61 | "import/extensions": "off" 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/browser.js: -------------------------------------------------------------------------------- 1 | /* eslint-env browser */ 2 | 3 | /** 4 | * This is the web browser implementation of `debug()`. 5 | */ 6 | 7 | exports.formatArgs = formatArgs; 8 | exports.save = save; 9 | exports.load = load; 10 | exports.useColors = useColors; 11 | exports.storage = localstorage(); 12 | exports.destroy = (() => { 13 | let warned = false; 14 | 15 | return () => { 16 | if (!warned) { 17 | warned = true; 18 | console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); 19 | } 20 | }; 21 | })(); 22 | 23 | /** 24 | * Colors. 25 | */ 26 | 27 | exports.colors = [ 28 | '#0000CC', 29 | '#0000FF', 30 | '#0033CC', 31 | '#0033FF', 32 | '#0066CC', 33 | '#0066FF', 34 | '#0099CC', 35 | '#0099FF', 36 | '#00CC00', 37 | '#00CC33', 38 | '#00CC66', 39 | '#00CC99', 40 | '#00CCCC', 41 | '#00CCFF', 42 | '#3300CC', 43 | '#3300FF', 44 | '#3333CC', 45 | '#3333FF', 46 | '#3366CC', 47 | '#3366FF', 48 | '#3399CC', 49 | '#3399FF', 50 | '#33CC00', 51 | '#33CC33', 52 | '#33CC66', 53 | '#33CC99', 54 | '#33CCCC', 55 | '#33CCFF', 56 | '#6600CC', 57 | '#6600FF', 58 | '#6633CC', 59 | '#6633FF', 60 | '#66CC00', 61 | '#66CC33', 62 | '#9900CC', 63 | '#9900FF', 64 | '#9933CC', 65 | '#9933FF', 66 | '#99CC00', 67 | '#99CC33', 68 | '#CC0000', 69 | '#CC0033', 70 | '#CC0066', 71 | '#CC0099', 72 | '#CC00CC', 73 | '#CC00FF', 74 | '#CC3300', 75 | '#CC3333', 76 | '#CC3366', 77 | '#CC3399', 78 | '#CC33CC', 79 | '#CC33FF', 80 | '#CC6600', 81 | '#CC6633', 82 | '#CC9900', 83 | '#CC9933', 84 | '#CCCC00', 85 | '#CCCC33', 86 | '#FF0000', 87 | '#FF0033', 88 | '#FF0066', 89 | '#FF0099', 90 | '#FF00CC', 91 | '#FF00FF', 92 | '#FF3300', 93 | '#FF3333', 94 | '#FF3366', 95 | '#FF3399', 96 | '#FF33CC', 97 | '#FF33FF', 98 | '#FF6600', 99 | '#FF6633', 100 | '#FF9900', 101 | '#FF9933', 102 | '#FFCC00', 103 | '#FFCC33' 104 | ]; 105 | 106 | /** 107 | * Currently only WebKit-based Web Inspectors, Firefox >= v31, 108 | * and the Firebug extension (any Firefox version) are known 109 | * to support "%c" CSS customizations. 110 | * 111 | * TODO: add a `localStorage` variable to explicitly enable/disable colors 112 | */ 113 | 114 | // eslint-disable-next-line complexity 115 | function useColors() { 116 | // NB: In an Electron preload script, document will be defined but not fully 117 | // initialized. Since we know we're in Chrome, we'll just detect this case 118 | // explicitly 119 | if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { 120 | return true; 121 | } 122 | 123 | // Internet Explorer and Edge do not support colors. 124 | if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { 125 | return false; 126 | } 127 | 128 | let m; 129 | 130 | // Is webkit? http://stackoverflow.com/a/16459606/376773 131 | // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 132 | // eslint-disable-next-line no-return-assign 133 | return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || 134 | // Is firebug? http://stackoverflow.com/a/398120/376773 135 | (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || 136 | // Is firefox >= v31? 137 | // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages 138 | (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || 139 | // Double check webkit in userAgent just in case we are in a worker 140 | (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); 141 | } 142 | 143 | /** 144 | * Colorize log arguments if enabled. 145 | * 146 | * @api public 147 | */ 148 | 149 | function formatArgs(args) { 150 | args[0] = (this.useColors ? '%c' : '') + 151 | this.namespace + 152 | (this.useColors ? ' %c' : ' ') + 153 | args[0] + 154 | (this.useColors ? '%c ' : ' ') + 155 | '+' + module.exports.humanize(this.diff); 156 | 157 | if (!this.useColors) { 158 | return; 159 | } 160 | 161 | const c = 'color: ' + this.color; 162 | args.splice(1, 0, c, 'color: inherit'); 163 | 164 | // The final "%c" is somewhat tricky, because there could be other 165 | // arguments passed either before or after the %c, so we need to 166 | // figure out the correct index to insert the CSS into 167 | let index = 0; 168 | let lastC = 0; 169 | args[0].replace(/%[a-zA-Z%]/g, match => { 170 | if (match === '%%') { 171 | return; 172 | } 173 | index++; 174 | if (match === '%c') { 175 | // We only are interested in the *last* %c 176 | // (the user may have provided their own) 177 | lastC = index; 178 | } 179 | }); 180 | 181 | args.splice(lastC, 0, c); 182 | } 183 | 184 | /** 185 | * Invokes `console.debug()` when available. 186 | * No-op when `console.debug` is not a "function". 187 | * If `console.debug` is not available, falls back 188 | * to `console.log`. 189 | * 190 | * @api public 191 | */ 192 | exports.log = console.debug || console.log || (() => {}); 193 | 194 | /** 195 | * Save `namespaces`. 196 | * 197 | * @param {String} namespaces 198 | * @api private 199 | */ 200 | function save(namespaces) { 201 | try { 202 | if (namespaces) { 203 | exports.storage.setItem('debug', namespaces); 204 | } else { 205 | exports.storage.removeItem('debug'); 206 | } 207 | } catch (error) { 208 | // Swallow 209 | // XXX (@Qix-) should we be logging these? 210 | } 211 | } 212 | 213 | /** 214 | * Load `namespaces`. 215 | * 216 | * @return {String} returns the previously persisted debug modes 217 | * @api private 218 | */ 219 | function load() { 220 | let r; 221 | try { 222 | r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ; 223 | } catch (error) { 224 | // Swallow 225 | // XXX (@Qix-) should we be logging these? 226 | } 227 | 228 | // If debug isn't set in LS, and we're in Electron, try to load $DEBUG 229 | if (!r && typeof process !== 'undefined' && 'env' in process) { 230 | r = process.env.DEBUG; 231 | } 232 | 233 | return r; 234 | } 235 | 236 | /** 237 | * Localstorage attempts to return the localstorage. 238 | * 239 | * This is necessary because safari throws 240 | * when a user disables cookies/localstorage 241 | * and you attempt to access it. 242 | * 243 | * @return {LocalStorage} 244 | * @api private 245 | */ 246 | 247 | function localstorage() { 248 | try { 249 | // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context 250 | // The Browser also has localStorage in the global context. 251 | return localStorage; 252 | } catch (error) { 253 | // Swallow 254 | // XXX (@Qix-) should we be logging these? 255 | } 256 | } 257 | 258 | module.exports = require('./common')(exports); 259 | 260 | const {formatters} = module.exports; 261 | 262 | /** 263 | * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. 264 | */ 265 | 266 | formatters.j = function (v) { 267 | try { 268 | return JSON.stringify(v); 269 | } catch (error) { 270 | return '[UnexpectedJSONParseError]: ' + error.message; 271 | } 272 | }; 273 | -------------------------------------------------------------------------------- /src/common.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * This is the common logic for both the Node.js and web browser 4 | * implementations of `debug()`. 5 | */ 6 | 7 | function setup(env) { 8 | createDebug.debug = createDebug; 9 | createDebug.default = createDebug; 10 | createDebug.coerce = coerce; 11 | createDebug.disable = disable; 12 | createDebug.enable = enable; 13 | createDebug.enabled = enabled; 14 | createDebug.humanize = require('ms'); 15 | createDebug.destroy = destroy; 16 | 17 | Object.keys(env).forEach(key => { 18 | createDebug[key] = env[key]; 19 | }); 20 | 21 | /** 22 | * The currently active debug mode names, and names to skip. 23 | */ 24 | 25 | createDebug.names = []; 26 | createDebug.skips = []; 27 | 28 | /** 29 | * Map of special "%n" handling functions, for the debug "format" argument. 30 | * 31 | * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". 32 | */ 33 | createDebug.formatters = {}; 34 | 35 | /** 36 | * Selects a color for a debug namespace 37 | * @param {String} namespace The namespace string for the debug instance to be colored 38 | * @return {Number|String} An ANSI color code for the given namespace 39 | * @api private 40 | */ 41 | function selectColor(namespace) { 42 | let hash = 0; 43 | 44 | for (let i = 0; i < namespace.length; i++) { 45 | hash = ((hash << 5) - hash) + namespace.charCodeAt(i); 46 | hash |= 0; // Convert to 32bit integer 47 | } 48 | 49 | return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; 50 | } 51 | createDebug.selectColor = selectColor; 52 | 53 | /** 54 | * Create a debugger with the given `namespace`. 55 | * 56 | * @param {String} namespace 57 | * @return {Function} 58 | * @api public 59 | */ 60 | function createDebug(namespace) { 61 | let prevTime; 62 | let enableOverride = null; 63 | let namespacesCache; 64 | let enabledCache; 65 | 66 | function debug(...args) { 67 | // Disabled? 68 | if (!debug.enabled) { 69 | return; 70 | } 71 | 72 | const self = debug; 73 | 74 | // Set `diff` timestamp 75 | const curr = Number(new Date()); 76 | const ms = curr - (prevTime || curr); 77 | self.diff = ms; 78 | self.prev = prevTime; 79 | self.curr = curr; 80 | prevTime = curr; 81 | 82 | args[0] = createDebug.coerce(args[0]); 83 | 84 | if (typeof args[0] !== 'string') { 85 | // Anything else let's inspect with %O 86 | args.unshift('%O'); 87 | } 88 | 89 | // Apply any `formatters` transformations 90 | let index = 0; 91 | args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { 92 | // If we encounter an escaped % then don't increase the array index 93 | if (match === '%%') { 94 | return '%'; 95 | } 96 | index++; 97 | const formatter = createDebug.formatters[format]; 98 | if (typeof formatter === 'function') { 99 | const val = args[index]; 100 | match = formatter.call(self, val); 101 | 102 | // Now we need to remove `args[index]` since it's inlined in the `format` 103 | args.splice(index, 1); 104 | index--; 105 | } 106 | return match; 107 | }); 108 | 109 | // Apply env-specific formatting (colors, etc.) 110 | createDebug.formatArgs.call(self, args); 111 | 112 | const logFn = self.log || createDebug.log; 113 | logFn.apply(self, args); 114 | } 115 | 116 | debug.namespace = namespace; 117 | debug.useColors = createDebug.useColors(); 118 | debug.color = createDebug.selectColor(namespace); 119 | debug.extend = extend; 120 | debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. 121 | 122 | Object.defineProperty(debug, 'enabled', { 123 | enumerable: true, 124 | configurable: false, 125 | get: () => { 126 | if (enableOverride !== null) { 127 | return enableOverride; 128 | } 129 | if (namespacesCache !== createDebug.namespaces) { 130 | namespacesCache = createDebug.namespaces; 131 | enabledCache = createDebug.enabled(namespace); 132 | } 133 | 134 | return enabledCache; 135 | }, 136 | set: v => { 137 | enableOverride = v; 138 | } 139 | }); 140 | 141 | // Env-specific initialization logic for debug instances 142 | if (typeof createDebug.init === 'function') { 143 | createDebug.init(debug); 144 | } 145 | 146 | return debug; 147 | } 148 | 149 | function extend(namespace, delimiter) { 150 | const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); 151 | newDebug.log = this.log; 152 | return newDebug; 153 | } 154 | 155 | /** 156 | * Enables a debug mode by namespaces. This can include modes 157 | * separated by a colon and wildcards. 158 | * 159 | * @param {String} namespaces 160 | * @api public 161 | */ 162 | function enable(namespaces) { 163 | createDebug.save(namespaces); 164 | createDebug.namespaces = namespaces; 165 | 166 | createDebug.names = []; 167 | createDebug.skips = []; 168 | 169 | const split = (typeof namespaces === 'string' ? namespaces : '') 170 | .trim() 171 | .replace(/\s+/g, ',') 172 | .split(',') 173 | .filter(Boolean); 174 | 175 | for (const ns of split) { 176 | if (ns[0] === '-') { 177 | createDebug.skips.push(ns.slice(1)); 178 | } else { 179 | createDebug.names.push(ns); 180 | } 181 | } 182 | } 183 | 184 | /** 185 | * Checks if the given string matches a namespace template, honoring 186 | * asterisks as wildcards. 187 | * 188 | * @param {String} search 189 | * @param {String} template 190 | * @return {Boolean} 191 | */ 192 | function matchesTemplate(search, template) { 193 | let searchIndex = 0; 194 | let templateIndex = 0; 195 | let starIndex = -1; 196 | let matchIndex = 0; 197 | 198 | while (searchIndex < search.length) { 199 | if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { 200 | // Match character or proceed with wildcard 201 | if (template[templateIndex] === '*') { 202 | starIndex = templateIndex; 203 | matchIndex = searchIndex; 204 | templateIndex++; // Skip the '*' 205 | } else { 206 | searchIndex++; 207 | templateIndex++; 208 | } 209 | } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition 210 | // Backtrack to the last '*' and try to match more characters 211 | templateIndex = starIndex + 1; 212 | matchIndex++; 213 | searchIndex = matchIndex; 214 | } else { 215 | return false; // No match 216 | } 217 | } 218 | 219 | // Handle trailing '*' in template 220 | while (templateIndex < template.length && template[templateIndex] === '*') { 221 | templateIndex++; 222 | } 223 | 224 | return templateIndex === template.length; 225 | } 226 | 227 | /** 228 | * Disable debug output. 229 | * 230 | * @return {String} namespaces 231 | * @api public 232 | */ 233 | function disable() { 234 | const namespaces = [ 235 | ...createDebug.names, 236 | ...createDebug.skips.map(namespace => '-' + namespace) 237 | ].join(','); 238 | createDebug.enable(''); 239 | return namespaces; 240 | } 241 | 242 | /** 243 | * Returns true if the given mode name is enabled, false otherwise. 244 | * 245 | * @param {String} name 246 | * @return {Boolean} 247 | * @api public 248 | */ 249 | function enabled(name) { 250 | for (const skip of createDebug.skips) { 251 | if (matchesTemplate(name, skip)) { 252 | return false; 253 | } 254 | } 255 | 256 | for (const ns of createDebug.names) { 257 | if (matchesTemplate(name, ns)) { 258 | return true; 259 | } 260 | } 261 | 262 | return false; 263 | } 264 | 265 | /** 266 | * Coerce `val`. 267 | * 268 | * @param {Mixed} val 269 | * @return {Mixed} 270 | * @api private 271 | */ 272 | function coerce(val) { 273 | if (val instanceof Error) { 274 | return val.stack || val.message; 275 | } 276 | return val; 277 | } 278 | 279 | /** 280 | * XXX DO NOT USE. This is a temporary stub function. 281 | * XXX It WILL be removed in the next major release. 282 | */ 283 | function destroy() { 284 | console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); 285 | } 286 | 287 | createDebug.enable(createDebug.load()); 288 | 289 | return createDebug; 290 | } 291 | 292 | module.exports = setup; 293 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Detect Electron renderer / nwjs process, which is node, but we should 3 | * treat as a browser. 4 | */ 5 | 6 | if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { 7 | module.exports = require('./browser.js'); 8 | } else { 9 | module.exports = require('./node.js'); 10 | } 11 | -------------------------------------------------------------------------------- /src/node.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Module dependencies. 3 | */ 4 | 5 | const tty = require('tty'); 6 | const util = require('util'); 7 | 8 | /** 9 | * This is the Node.js implementation of `debug()`. 10 | */ 11 | 12 | exports.init = init; 13 | exports.log = log; 14 | exports.formatArgs = formatArgs; 15 | exports.save = save; 16 | exports.load = load; 17 | exports.useColors = useColors; 18 | exports.destroy = util.deprecate( 19 | () => {}, 20 | 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' 21 | ); 22 | 23 | /** 24 | * Colors. 25 | */ 26 | 27 | exports.colors = [6, 2, 3, 4, 5, 1]; 28 | 29 | try { 30 | // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) 31 | // eslint-disable-next-line import/no-extraneous-dependencies 32 | const supportsColor = require('supports-color'); 33 | 34 | if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { 35 | exports.colors = [ 36 | 20, 37 | 21, 38 | 26, 39 | 27, 40 | 32, 41 | 33, 42 | 38, 43 | 39, 44 | 40, 45 | 41, 46 | 42, 47 | 43, 48 | 44, 49 | 45, 50 | 56, 51 | 57, 52 | 62, 53 | 63, 54 | 68, 55 | 69, 56 | 74, 57 | 75, 58 | 76, 59 | 77, 60 | 78, 61 | 79, 62 | 80, 63 | 81, 64 | 92, 65 | 93, 66 | 98, 67 | 99, 68 | 112, 69 | 113, 70 | 128, 71 | 129, 72 | 134, 73 | 135, 74 | 148, 75 | 149, 76 | 160, 77 | 161, 78 | 162, 79 | 163, 80 | 164, 81 | 165, 82 | 166, 83 | 167, 84 | 168, 85 | 169, 86 | 170, 87 | 171, 88 | 172, 89 | 173, 90 | 178, 91 | 179, 92 | 184, 93 | 185, 94 | 196, 95 | 197, 96 | 198, 97 | 199, 98 | 200, 99 | 201, 100 | 202, 101 | 203, 102 | 204, 103 | 205, 104 | 206, 105 | 207, 106 | 208, 107 | 209, 108 | 214, 109 | 215, 110 | 220, 111 | 221 112 | ]; 113 | } 114 | } catch (error) { 115 | // Swallow - we only care if `supports-color` is available; it doesn't have to be. 116 | } 117 | 118 | /** 119 | * Build up the default `inspectOpts` object from the environment variables. 120 | * 121 | * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js 122 | */ 123 | 124 | exports.inspectOpts = Object.keys(process.env).filter(key => { 125 | return /^debug_/i.test(key); 126 | }).reduce((obj, key) => { 127 | // Camel-case 128 | const prop = key 129 | .substring(6) 130 | .toLowerCase() 131 | .replace(/_([a-z])/g, (_, k) => { 132 | return k.toUpperCase(); 133 | }); 134 | 135 | // Coerce string value into JS value 136 | let val = process.env[key]; 137 | if (/^(yes|on|true|enabled)$/i.test(val)) { 138 | val = true; 139 | } else if (/^(no|off|false|disabled)$/i.test(val)) { 140 | val = false; 141 | } else if (val === 'null') { 142 | val = null; 143 | } else { 144 | val = Number(val); 145 | } 146 | 147 | obj[prop] = val; 148 | return obj; 149 | }, {}); 150 | 151 | /** 152 | * Is stdout a TTY? Colored output is enabled when `true`. 153 | */ 154 | 155 | function useColors() { 156 | return 'colors' in exports.inspectOpts ? 157 | Boolean(exports.inspectOpts.colors) : 158 | tty.isatty(process.stderr.fd); 159 | } 160 | 161 | /** 162 | * Adds ANSI color escape codes if enabled. 163 | * 164 | * @api public 165 | */ 166 | 167 | function formatArgs(args) { 168 | const {namespace: name, useColors} = this; 169 | 170 | if (useColors) { 171 | const c = this.color; 172 | const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); 173 | const prefix = ` ${colorCode};1m${name} \u001B[0m`; 174 | 175 | args[0] = prefix + args[0].split('\n').join('\n' + prefix); 176 | args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); 177 | } else { 178 | args[0] = getDate() + name + ' ' + args[0]; 179 | } 180 | } 181 | 182 | function getDate() { 183 | if (exports.inspectOpts.hideDate) { 184 | return ''; 185 | } 186 | return new Date().toISOString() + ' '; 187 | } 188 | 189 | /** 190 | * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. 191 | */ 192 | 193 | function log(...args) { 194 | return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); 195 | } 196 | 197 | /** 198 | * Save `namespaces`. 199 | * 200 | * @param {String} namespaces 201 | * @api private 202 | */ 203 | function save(namespaces) { 204 | if (namespaces) { 205 | process.env.DEBUG = namespaces; 206 | } else { 207 | // If you set a process.env field to null or undefined, it gets cast to the 208 | // string 'null' or 'undefined'. Just delete instead. 209 | delete process.env.DEBUG; 210 | } 211 | } 212 | 213 | /** 214 | * Load `namespaces`. 215 | * 216 | * @return {String} returns the previously persisted debug modes 217 | * @api private 218 | */ 219 | 220 | function load() { 221 | return process.env.DEBUG; 222 | } 223 | 224 | /** 225 | * Init logic for `debug` instances. 226 | * 227 | * Create a new `inspectOpts` object in case `useColors` is set 228 | * differently for a particular `debug` instance. 229 | */ 230 | 231 | function init(debug) { 232 | debug.inspectOpts = {}; 233 | 234 | const keys = Object.keys(exports.inspectOpts); 235 | for (let i = 0; i < keys.length; i++) { 236 | debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; 237 | } 238 | } 239 | 240 | module.exports = require('./common')(exports); 241 | 242 | const {formatters} = module.exports; 243 | 244 | /** 245 | * Map %o to `util.inspect()`, all on a single line. 246 | */ 247 | 248 | formatters.o = function (v) { 249 | this.inspectOpts.colors = this.useColors; 250 | return util.inspect(v, this.inspectOpts) 251 | .split('\n') 252 | .map(str => str.trim()) 253 | .join(' '); 254 | }; 255 | 256 | /** 257 | * Map %O to `util.inspect()`, allowing multiple lines if needed. 258 | */ 259 | 260 | formatters.O = function (v) { 261 | this.inspectOpts.colors = this.useColors; 262 | return util.inspect(v, this.inspectOpts); 263 | }; 264 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | const assert = require('assert'); 4 | const debug = require('./src'); 5 | 6 | describe('debug', () => { 7 | it('passes a basic sanity check', () => { 8 | const log = debug('test'); 9 | log.enabled = true; 10 | log.log = () => {}; 11 | 12 | assert.doesNotThrow(() => log('hello world')); 13 | }); 14 | 15 | it('allows namespaces to be a non-string value', () => { 16 | const log = debug('test'); 17 | log.enabled = true; 18 | log.log = () => {}; 19 | 20 | assert.doesNotThrow(() => debug.enable(true)); 21 | }); 22 | 23 | it('honors global debug namespace enable calls', () => { 24 | assert.deepStrictEqual(debug('test:12345').enabled, false); 25 | assert.deepStrictEqual(debug('test:67890').enabled, false); 26 | 27 | debug.enable('test:12345'); 28 | assert.deepStrictEqual(debug('test:12345').enabled, true); 29 | assert.deepStrictEqual(debug('test:67890').enabled, false); 30 | }); 31 | 32 | it('uses custom log function', () => { 33 | const log = debug('test'); 34 | log.enabled = true; 35 | 36 | const messages = []; 37 | log.log = (...args) => messages.push(args); 38 | 39 | log('using custom log function'); 40 | log('using custom log function again'); 41 | log('%O', 12345); 42 | 43 | assert.deepStrictEqual(messages.length, 3); 44 | }); 45 | 46 | describe('extend namespace', () => { 47 | it('should extend namespace', () => { 48 | const log = debug('foo'); 49 | log.enabled = true; 50 | log.log = () => {}; 51 | 52 | const logBar = log.extend('bar'); 53 | assert.deepStrictEqual(logBar.namespace, 'foo:bar'); 54 | }); 55 | 56 | it('should extend namespace with custom delimiter', () => { 57 | const log = debug('foo'); 58 | log.enabled = true; 59 | log.log = () => {}; 60 | 61 | const logBar = log.extend('bar', '--'); 62 | assert.deepStrictEqual(logBar.namespace, 'foo--bar'); 63 | }); 64 | 65 | it('should extend namespace with empty delimiter', () => { 66 | const log = debug('foo'); 67 | log.enabled = true; 68 | log.log = () => {}; 69 | 70 | const logBar = log.extend('bar', ''); 71 | assert.deepStrictEqual(logBar.namespace, 'foobar'); 72 | }); 73 | 74 | it('should keep the log function between extensions', () => { 75 | const log = debug('foo'); 76 | log.log = () => {}; 77 | 78 | const logBar = log.extend('bar'); 79 | assert.deepStrictEqual(log.log, logBar.log); 80 | }); 81 | }); 82 | 83 | describe('rebuild namespaces string (disable)', () => { 84 | it('handle names, skips, and wildcards', () => { 85 | debug.enable('test,abc*,-abc'); 86 | const namespaces = debug.disable(); 87 | assert.deepStrictEqual(namespaces, 'test,abc*,-abc'); 88 | }); 89 | 90 | it('handles empty', () => { 91 | debug.enable(''); 92 | const namespaces = debug.disable(); 93 | assert.deepStrictEqual(namespaces, ''); 94 | assert.deepStrictEqual(debug.names, []); 95 | assert.deepStrictEqual(debug.skips, []); 96 | }); 97 | 98 | it('handles all', () => { 99 | debug.enable('*'); 100 | const namespaces = debug.disable(); 101 | assert.deepStrictEqual(namespaces, '*'); 102 | }); 103 | 104 | it('handles skip all', () => { 105 | debug.enable('-*'); 106 | const namespaces = debug.disable(); 107 | assert.deepStrictEqual(namespaces, '-*'); 108 | }); 109 | 110 | it('names+skips same with new string', () => { 111 | debug.enable('test,abc*,-abc'); 112 | const oldNames = [...debug.names]; 113 | const oldSkips = [...debug.skips]; 114 | const namespaces = debug.disable(); 115 | assert.deepStrictEqual(namespaces, 'test,abc*,-abc'); 116 | debug.enable(namespaces); 117 | assert.deepStrictEqual(oldNames.map(String), debug.names.map(String)); 118 | assert.deepStrictEqual(oldSkips.map(String), debug.skips.map(String)); 119 | }); 120 | 121 | it('handles re-enabling existing instances', () => { 122 | debug.disable('*'); 123 | const inst = debug('foo'); 124 | const messages = []; 125 | inst.log = msg => messages.push(msg.replace(/^[^@]*@([^@]+)@.*$/, '$1')); 126 | 127 | inst('@test@'); 128 | assert.deepStrictEqual(messages, []); 129 | debug.enable('foo'); 130 | assert.deepStrictEqual(messages, []); 131 | inst('@test2@'); 132 | assert.deepStrictEqual(messages, ['test2']); 133 | inst('@test3@'); 134 | assert.deepStrictEqual(messages, ['test2', 'test3']); 135 | debug.disable('*'); 136 | inst('@test4@'); 137 | assert.deepStrictEqual(messages, ['test2', 'test3']); 138 | }); 139 | }); 140 | }); 141 | -------------------------------------------------------------------------------- /test.node.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | const assert = require('assert'); 4 | const util = require('util'); 5 | const sinon = require('sinon'); 6 | const debug = require('./src/node'); 7 | 8 | const formatWithOptionsSpy = sinon.spy(util, 'formatWithOptions'); 9 | beforeEach(() => { 10 | formatWithOptionsSpy.resetHistory(); 11 | }); 12 | 13 | describe('debug node', () => { 14 | describe('formatting options', () => { 15 | it('calls util.formatWithOptions', () => { 16 | debug.enable('*'); 17 | const stdErrWriteStub = sinon.stub(process.stderr, 'write'); 18 | const log = debug('formatting options'); 19 | log('hello world'); 20 | assert(util.formatWithOptions.callCount === 1); 21 | stdErrWriteStub.restore(); 22 | }); 23 | 24 | it('calls util.formatWithOptions with inspectOpts', () => { 25 | debug.enable('*'); 26 | const options = { 27 | hideDate: true, 28 | colors: true, 29 | depth: 10, 30 | showHidden: true 31 | }; 32 | Object.assign(debug.inspectOpts, options); 33 | const stdErrWriteStub = sinon.stub(process.stderr, 'write'); 34 | const log = debug('format with inspectOpts'); 35 | log('hello world2'); 36 | assert.deepStrictEqual(util.formatWithOptions.getCall(0).args[0], options); 37 | stdErrWriteStub.restore(); 38 | }); 39 | }); 40 | }); 41 | --------------------------------------------------------------------------------