简体   繁体   中英

How to log from a NPM package, without forcing a logging library

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:

  • log the error
  • call a callback with another error, not passing in the original error

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).

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

  1. Take zero dependency and provide these messages out of band eg using an event emitter
  2. Take a dependency on a logging library of your choice.

I would happily go with option 1. For TypeScript also I'd use a typesafe version eg https://basarat.gitbooks.io/typescript/docs/tips/typed-event.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM