Skip to content

Commit

Permalink
add instance extends feature (#524)
Browse files Browse the repository at this point in the history
* instance extends feature

* add .extend documentation

* allow empty delimiter in extend
  • Loading branch information
kwolfy authored and Qix- committed Sep 11, 2018
1 parent 207a6a2 commit e43e5fe
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Expand Up @@ -268,6 +268,20 @@ error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```

## Extend
You can simply extend debugger
```js
const log = require('debug')('auth');

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

log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello
```

## Set dynamically

You can also enable debug dynamically by calling the `enable()` method :
Expand Down
5 changes: 5 additions & 0 deletions src/common.js
Expand Up @@ -123,6 +123,7 @@ module.exports = function setup(env) {
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.extend = extend;
//debug.formatArgs = formatArgs;
//debug.rawLog = rawLog;

Expand All @@ -146,6 +147,10 @@ module.exports = function setup(env) {
}
}

function extend (namespace, delimiter) {
return createDebug(this.namespace + (typeof delimiter !== 'undefined' ? delimiter : ':') + namespace);
}

/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
Expand Down
26 changes: 26 additions & 0 deletions test/debug_spec.js
Expand Up @@ -64,4 +64,30 @@ describe('debug', function () {
});
});


describe('extend namespace', function () {
var log;

beforeEach(function () {
debug.enable('foo');
log = debug('foo');
});

it('should extend namespace', function () {
var logBar = log.extend('bar');
expect(logBar.namespace).to.be.equal('foo:bar');
});

it('should extend namespace with custom delimiter', function () {
var logBar = log.extend('bar', '--');
expect(logBar.namespace).to.be.equal('foo--bar');
});

it('should extend namespace with empty delimiter', function () {
var logBar = log.extend('bar', '');
expect(logBar.namespace).to.be.equal('foobar');
});

});

});

0 comments on commit e43e5fe

Please sign in to comment.