I'm writing a company npm package (in typescript), and porting existing code into it. In the existing code, there are some console.log
, console.warn
and console.error
statements. Like this:
try {
const foo = getFoo("bar");
return callback(undefined, foo);
} catch (e) {
console.error(e);
return cb(new httpErrors.BadRequest("Some message"));
}
So what is happening is:
This is the behavior we want, as we don't want to return the original error message, but we do want it in our logs.
Now that I'm moving to a package, I want to apply some best practices and remove the console
calls. This is a tslint rule and I agree that it isn't up to the package author to fill the logs of the package user.
So what would be the best approach here?
I've read about the debug
package, but that's for development purposes only. Plus, that would mean we wouldn't have our log messages unless we set DEBUG=...
I'm wondering if using a singleton EventEmitter
in my package is an option. But then again, singleton is regarded as an antipattern.
And I don't want to add a logging library as a dependency, because as the package author, it's not up to me to say which logging library to use.
A last option I've thought about is to allow passing in a logging function that I can then call, but it feels a bit crummy to me.
So what is the preferred technique to allow messages to be logged from a (TypeScript/npm) library?
(If there is one at all; I'm fairly new to the Node/TypeScript ecosystem).
With your NPM package local to your machine, you'll need a way to reference/install it in the test application. Inside of the original NPM package directory, run npm link from the command line. This command will allow us to simulate installing this NPM package without it actually being published.
log and console.The built-in console module in Node. js lets you write log messages to standard output (stdout) and standard error (stderr)using the log and error functions, respectively.
When a package fails to install or publish, the npm CLI will generate an npm-debug. log file. This log file can help you figure out what went wrong. If you need to generate a npm-debug. log file, you can run one of these commands.
Logging in Node. By default, it will not produce any output. To enable this logger, you have run your application with a special environment variable, called DEBUG . Once you do that, the debug module will come to life and will start producing log events for stdout.
So what is the preferred technique to allow messages to be logged from a (TypeScript/npm) library?
You want to handle the default error behaviour, and yet allow the consumer an opportunity to look at the error messages.
Your options literally are
I would happily go with option 1. For TypeScript also I'd use a typesafe version e.g. https://basarat.gitbooks.io/typescript/docs/tips/typed-event.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With