Wouldn't be useful to be able to enable and disable debug mode programmatically from node scripts?
debug.enable()
debug.disable()
+1
You can work around it like this:
require('debug').enable('myapp:somenamespace'); //enable namespace
debug = require('debug')('myapp:somenamespace'); //reload debug
I don't know if we mean the same thing. Actually I did something like that:
// enable
process.env.DEBUG = '*';
var debug = require('debug')('namespace');
debug('printed');
// disable
delete process.env.DEBUG;
var debug = require('debug')('namespace');
debug('not printed');
It's the same thing!
But I think my solution adds the namespace, while yours replaces it? Don't know for sure...
Generally speaking, the debug modules will not work if you do not use a DEBUG envroinment variable. Correct me if I'm wrong.
@ernie58 - your workaround was quite useful. I wanted to make sure that any errors I have, will always get logged (let's skip the pros/cons of console.error) even if the namespace isn't turned on explicitly. I'm sharing the function where I wrapped your workaround for use in my code:
/**
* Creates a debug logger object for a given scope (a.k.a. namespace)
* and if the level of logging happens to be `error` then programatically
* enables that namespace.
*
* Wanting to always enable errors, led to a minor implementation change
* such that now log_level (only for error) also gets added to the namespace dynamically.
*
* So if DEBUG does not enable `my:namespace` explicitly, even then:
* > my:namespace:error (will be enabled)
* ... but `my:namespace` will be left as disabled.
*
* @param level
* @param scope
* @returns {*}
*/
function createLogger(level, scope){
/* NOTE: Moved it, in order to create fewer objects.
* If left here, then we would end up with separate objects for
* > my:namespace:info
* > my:namespace:debug
* > my:namespace:trace
* as well!
*/
//scope += ':' + level;
// enable namespace programmatically
// https://github.com/visionmedia/debug/issues/275
if (level === 'error') {
scope += ':' + level;
console.log('will try to enable namespace:', scope);
// NOTE: the goal is to enable `my:namespace:error` when DEBUG is not set for `my:namespace`
// but this code will run even when `DEBUG=my:namespace` ...
// Yet it doesn't seem to cause any problems or conflict so its fine, I suppose.
require('debug').enable(scope);
}
var logger;
if (scope) {
logger = debug(scope);
} else {
logger = debug;
}
return logger;
}
great!
Most helpful comment
I don't know if we mean the same thing. Actually I did something like that: