Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: debug-js/debug
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 3ad8df75614cd4306709ad73519fd579971fb8d9
Choose a base ref
...
head repository: debug-js/debug
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: b82d4e6c799198b3d39b05265bf68da9a9aacd41
Choose a head ref
  • 7 commits
  • 8 files changed
  • 5 contributors

Commits on Nov 22, 2016

  1. Revert "handle regex special characters"

    This reverts commit 8dd8345.
    
    We shouldn't have changed the original behavior, which
    too many people are relying on at this point.
    
    It's also technically a breaking change, which we shouldn't
    have landed on a minor/patch version change. So in the interest
    of not breaking people's logs in production, reverting this.
    
    We can discuss in a new issue if we want to restore this patch
    for a `v3` release, but at the moment I'm personally leaningo
    towards *no*, for historical reasons (i.e. this is reminding
    me of Node.js trying to remove `sys` if anybody reading this
    remembers those days).
    
    See the discussion in #250 for more backlog.
    TooTallNate committed Nov 22, 2016
    Copy the full SHA
    e2a1955 View commit details

Commits on Dec 6, 2016

  1. Use same color for same namespace. (#338)

    * Use same color for same namespace.
    
    CF #258
    
    * Remove unused var.
    lchenay authored and thebigredgeek committed Dec 6, 2016
    Copy the full SHA
    501521f View commit details

Commits on Dec 12, 2016

  1. allow colours in workers (#335)

    botverse authored and thebigredgeek committed Dec 12, 2016
    Copy the full SHA
    bd9faa1 View commit details
  2. Node: %O (big O) pretty-prints the object (#322)

    * %O (big O) pretty-prints the object
    
    For example:
    
    ```js
    var debug = require('./')('foo')
    
    var o = {
      foo: 'bar',
      b: new Buffer(10),
      c: Math.PI
    }
    
    debug('%O', o)
    ```
    
    Previously:
    
    ```
      foo { foo: 'bar', b: <Buffer 01 00 00 00 01 00 00 00 c0 82>, c: 3.141592653589793 } +0ms
    ```
    
    Now:
    
    ```
      foo { foo: 'bar',
      foo   b: <Buffer 01 00 00 00 01 00 00 00 c0 82>,
      foo   c: 3.141592653589793 } +0ms
    ```
    
    This is a breaking change for anybody relying on the old `%O` behavior.
    Though I don't think `%O` was working previously because the formatters
    regexp wasn't checking for uppercase formatters (now fixed in this patch).
    
    * use %O by default if no formatting string is given
    
    * Readme: add Formatters section
    
    Fixes #302.
    
    * Readme: finish custom formatters example
    TooTallNate authored and thebigredgeek committed Dec 12, 2016
    Copy the full SHA
    00f3046 View commit details
  3. Node: configurable util.inspect() options (#327)

    * `formatArgs()` gets passed the args Array directly
    
    Rather than working on `arguments`. The Node.js version
    was for some reason turning the arguments into an Array
    again so it was happening twice! This should make things
    faster overall.
    
    * whitespace
    
    * rename `Readme.md` to `README.md`
    
    * refactor the `debug()` constructor a bit
    
    Now, debug instances are hot-enabelable. That is, you can
    toggle the `debug.enabled` boolean on instances to enable
    or disable an instance. There is still no global version of
    this functionality.
    
    Now all instances get a `useColors` and `colors` property,
    even disabled ones, in case they get enabled later on. Boot-up
    time impact should be negligible.
    
    * node: allow configurable `util.inspect()` options
    
    Via env variables by default. So to get more object depth,
    you pass the `DEBUG_DEPTH=10` env var.
    
    For the `showHidden` option, you set `DEBUG_SHOW_HIDDEN=on`.
    
    See the Node.js docs for the complete list of `util.inspect()` options:
    https://nodejs.org/api/util.html#util_util_inspect_object_options
    
    * README: document inspect env variables
    TooTallNate authored and thebigredgeek committed Dec 12, 2016
    3
    Copy the full SHA
    e58d54b View commit details
  4. Update bower.json (#342)

    Error thrown if using `bower.json` to require files.
    `.npmignore` contains `dist`.
    Justmatt authored and thebigredgeek committed Dec 12, 2016
    Copy the full SHA
    41002f1 View commit details

Commits on Dec 14, 2016

  1. release 2.4.0

    thebigredgeek committed Dec 14, 2016
    Copy the full SHA
    b82d4e6 View commit details
Showing with 166 additions and 82 deletions.
  1. +11 −0 CHANGELOG.md
  2. +53 −7 Readme.md → README.md
  3. +1 −1 bower.json
  4. +6 −7 browser.js
  5. +1 −1 component.json
  6. +33 −28 debug.js
  7. +60 −37 node.js
  8. +1 −1 package.json
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@

2.4.0 / 2016-12-13
==================

* Fix: bower.json references unbuilt src entry point (#342, @justmatt)
* Fix: revert "handle regex special characters" (@tootallnate)
* Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate)
* Feature: %O`(big O) pretty-prints objects (#322, @tootallnate)
* Improvement: allow colors in workers (#335, @botverse)
* Improvement: use same color for same namespace. (#338, @lchenay)

2.3.3 / 2016-11-09
==================

60 changes: 53 additions & 7 deletions Readme.md → README.md
Original file line number Diff line number Diff line change
@@ -79,14 +79,66 @@ Then, run the program to be debugged as usual.

## 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'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".

## 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:

| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disabled specific debugging namespaces. |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_FD`| File descriptor to output debug logs to. Defaults to stderr. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |


__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.

__Note:__ Certain IDEs (such as WebStorm) don't support colors on stderr. In these cases you must set `DEBUG_COLORS` to `1` and additionally change `DEBUG_FD` to `1`.

## Formatters


Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters:

| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |

### 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:

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

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

## Browser support

Debug works in the browser as well, 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`:
@@ -161,12 +213,6 @@ Example:
$ DEBUG_FD=3 node your-app.js 3> whatever.log
```

### Terminal colors

By default colors will only be used in a TTY. However this can be overridden by setting the environment variable `DEBUG_COLORS` to `1`.

Note: Certain IDEs (such as WebStorm) don't support colors on stderr. In these cases you must set `DEBUG_COLORS` to `1` and additionally change `DEBUG_FD` to `1`.

## Authors

- TJ Holowaychuk
2 changes: 1 addition & 1 deletion bower.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "visionmedia-debug",
"main": "dist/debug.js",
"main": "./debug.js",
"homepage": "https://github.com/visionmedia/debug",
"authors": [
"TJ Holowaychuk <tj@vision-media.ca>",
13 changes: 6 additions & 7 deletions browser.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

/**
* This is the web browser implementation of `debug()`.
*
@@ -42,10 +41,12 @@ function useColors() {
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
(typeof window !== 'undefined' && window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}

/**
@@ -67,8 +68,7 @@ exports.formatters.j = function(v) {
* @api public
*/

function formatArgs() {
var args = arguments;
function formatArgs(args) {
var useColors = this.useColors;

args[0] = (useColors ? '%c' : '')
@@ -99,7 +99,6 @@ function formatArgs() {
});

args.splice(lastC, 0, c);
return args;
}

/**
@@ -170,7 +169,7 @@ exports.enable(load());
* @api private
*/

function localstorage(){
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
2 changes: 1 addition & 1 deletion component.json
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@
"name": "debug",
"repo": "visionmedia/debug",
"description": "small debugging utility",
"version": "2.3.3",
"version": "2.4.0",
"keywords": [
"debug",
"log",
61 changes: 33 additions & 28 deletions debug.js
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@
* Expose `debug()` as the module.
*/

exports = module.exports = debug.debug = debug;
exports = module.exports = createDebug.debug = createDebug.default = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
@@ -23,7 +23,7 @@ exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/

exports.formatters = {};
@@ -42,13 +42,20 @@ var prevTime;

/**
* Select a color.
*
* @param {String} namespace
* @return {Number}
* @api private
*/

function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
function selectColor(namespace) {
var hash = 0, i;

for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}

return exports.colors[Math.abs(hash) % exports.colors.length];
}

/**
@@ -59,17 +66,13 @@ function selectColor() {
* @api public
*/

function debug(namespace) {
function createDebug(namespace) {

// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
function debug() {
// disabled?
if (!debug.enabled) return;

// define the `enabled` version
function enabled() {

var self = enabled;
var self = debug;

// set `diff` timestamp
var curr = +new Date();
@@ -79,10 +82,7 @@ function debug(namespace) {
self.curr = curr;
prevTime = curr;

// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();

// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
@@ -91,13 +91,13 @@ function debug(namespace) {
args[0] = exports.coerce(args[0]);

if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
// anything else let's inspect with %O
args.unshift('%O');
}

// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
@@ -113,19 +113,24 @@ function debug(namespace) {
return match;
});

// apply env-specific formatting
args = exports.formatArgs.apply(self, args);
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);

var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;

var fn = exports.enabled(namespace) ? enabled : disabled;
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespae);

fn.namespace = namespace;
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}

return fn;
return debug;
}

/**
@@ -144,7 +149,7 @@ function enable(namespaces) {

for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?');
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
97 changes: 60 additions & 37 deletions node.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

/**
* Module dependencies.
*/
@@ -13,6 +12,7 @@ var util = require('util');
*/

exports = module.exports = require('./debug');
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
@@ -25,6 +25,32 @@ exports.useColors = useColors;

exports.colors = [6, 2, 3, 4, 5, 1];

/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/

exports.inspectOpts = Object.keys(process.env).filter(function (key) {
return /^debug_/i.test(key);
}).reduce(function (obj, key) {
// camel-case
var prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/, function (_, k) { return k.toUpperCase() });

// coerce string value into JS value
var val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
else if (val === 'null') val = null;
else val = Number(val);

obj[prop] = val;
return obj;
}, {});

/**
* The file descriptor to write the `debug()` calls to.
* Set the `DEBUG_FD` env variable to override with another value. i.e.:
@@ -42,72 +68,58 @@ var stream = 1 === fd ? process.stdout :
*/

function useColors() {
var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase();
if (0 === debugColors.length) {
return tty.isatty(fd);
} else {
return '0' !== debugColors
&& 'no' !== debugColors
&& 'false' !== debugColors
&& 'disabled' !== debugColors;
}
return 'colors' in exports.inspectOpts
? Boolean(exports.inspectOpts.colors)
: tty.isatty(fd);
}

/**
* Map %o to `util.inspect()`, since Node doesn't do that out of the box.
* Map %o to `util.inspect()`, all on a single line.
*/

var inspect = (4 === util.inspect.length ?
// node <= 0.8.x
function (v, colors) {
return util.inspect(v, void 0, void 0, colors);
} :
// node > 0.8.x
function (v, colors) {
return util.inspect(v, { colors: colors });
}
);

exports.formatters.o = exports.formatters.O = function(v) {
return inspect(v, this.useColors)
exports.formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.replace(/\s*\n\s*/g, ' ');
};

/**
* Map %o to `util.inspect()`, allowing multiple lines if needed.
*/

exports.formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};

/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/

function formatArgs() {
var len = arguments.length;
var args = new Array(len);
var useColors = this.useColors;
function formatArgs(args) {
var name = this.namespace;
for (var i = 0; i < len; i++) {
args[i] = arguments[i];
}
var useColors = this.useColors;

if (useColors) {
var c = this.color;
var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';

args[0] = ' \u001b[3' + c + ';1m' + name + ' '
+ '\u001b[0m'
+ args[0];
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
} else {
args[0] = new Date().toUTCString()
+ ' ' + name + ' ' + args[0];
}
return args;
}

/**
* Invokes `console.error()` with the specified arguments.
* Invokes `util.format()` with the specified arguments and writes to `stream`.
*/

function log() {
return stream.write(util.format.apply(this, arguments) + '\n');
return stream.write(util.format.apply(util, arguments) + '\n');
}

/**
@@ -206,6 +218,17 @@ function createWritableStdioStream (fd) {
return stream;
}

/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/

function init (debug) {
debug.inspectOpts = util._extend({}, exports.inspectOpts);
}

/**
* Enable namespaces listed in `process.env.DEBUG` initially.
*/
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "debug",
"version": "2.3.3",
"version": "2.4.0",
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/debug.git"