Skip to content

Commit

Permalink
introduce debug.id helper method
Browse files Browse the repository at this point in the history
When debugging the applications that work with pools of streams
or sockets, the debug stream often comes out interleaved making it
impossible to distinguish between streams. It is a common knowledge
that unique `id`s could be assigned to each stream and be used in
logging to solve this. However, this solution is rather ad-hoc and
usually applied only during manual debugging.

This commit introduces standard function `debug.id()` that
increments the internal counter only when debugging is enabled, and
otherwise returns `undefined`.
  • Loading branch information
indutny committed Jan 23, 2018
1 parent 22f9932 commit 1141cf5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ module.exports = function setup(env) {

function createDebug(namespace) {
var prevTime;
var lastId = 0;

function debug() {
// disabled?
Expand Down Expand Up @@ -118,11 +119,19 @@ module.exports = function setup(env) {
logFn.apply(self, args);
}

function id () {
// disabled?
if (!debug.enabled) return;

return lastId++;
}

debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.id = id;
//debug.formatArgs = formatArgs;
//debug.rawLog = rawLog;

Expand Down
15 changes: 15 additions & 0 deletions test/debug_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,21 @@ describe('debug', function () {
expect(log.log).to.have.been.calledOnce;
});
});

context('with `log.id` function', function () {
it('increments internal id when enabled', function () {
expect(log.id()).to.equal(0);
expect(log.id()).to.equal(1);
expect(log.id()).to.equal(2);
});

it('does not increment internal id when disabled', function () {
debug.disable('test');

expect(log.id()).to.equal(undefined);
expect(log.id()).to.equal(undefined);
});
});
});

});

0 comments on commit 1141cf5

Please sign in to comment.