Explain chained method in order to implement a verbose mode
See original GitHub issueI think env-var is brilliant and it is my lightweight ‘go-to’ solution for (not surprisingly) environment variable reading.
However, one thing I like our node code to do is output what environment variables they are reading, and what values they are using (eg: from process.env or from a supplied default)
It seems a bit pointless putting in code like this every time:
if (process.env.RETRIES) console.log('Reading value for RETRIES from the environment'); const RETRIES = env.get('RETRIES').default(5).asInt(); ...
After struggling with various ways of implementing this in env-var, I came up with the idea for an .explain() method for the chain:
const RETRIES=env.get(''RETRIES).default(5).explain(console.debug).asInt();
If you don’t pass anything in the param, then console.debug is the default
I implemented it in variable.js:
/**
* Explain what is going on with the variable setting
* This is useful to people such as Docker admins, who may miss setting environment vars
* when they should - for example if the use is poorly documented
* @param {function} out
*/
explain: function (out) {
if (!out || typeof out !=='function') out=console.debug;
let assignedVal = container[varName];
if (assignedVal) {
out(`${varName} read from environment, value: ${assignedVal}`);
} else {
if (defValue) {
out(`${varName} not found in environment, using default value: ${defValue}`);
} else {
out(`${varName} cannot be read from environment, no default value specified`);
}
}
return accessors
}
Usage looks like this:
const RETRIES1 = env.get('RETRIES1').explain().asInt();
const RETRIES2 = env.get('RETRIES2').default(7).explain().asInt();
const RETRIES3 = env.get('RETRIES3').explain().asInt();
RETRIES1 read from environment, value: 15
RETRIES2 not found in environment, using default value: 7
RETRIES3 cannot be read from environment, no default value specified
Does this look like a useful feature? Have I implemented it in the best place?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:9 (7 by maintainers)
On balance I think the debug module is best here.
It’s common practice in the node community and it keeps the API of this module small.
I do like the proposed format of messages from above comments:
I’d be happy to accept a PR if anyone’s interested in it. I can get around to it in a week or so if not.
I like the idea for “debug” capability.
But I think having to add
explain
to every call is a bit verbose. On the other hand does allow for granularity, in case we report any secrets.I’m still leaving towards the global logger approach though.