diff --git a/README.md b/README.md index 8a3b70bf..1c6664ee 100644 --- a/README.md +++ b/README.md @@ -248,6 +248,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 : diff --git a/src/common.js b/src/common.js index 61eaf893..65713e4d 100644 --- a/src/common.js +++ b/src/common.js @@ -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; @@ -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. diff --git a/test/debug_spec.js b/test/debug_spec.js index 142fbe79..7ac6d7cd 100644 --- a/test/debug_spec.js +++ b/test/debug_spec.js @@ -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'); + }); + + }); + });