Peter
Peter

Reputation: 14118

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:

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

Upvotes: 12

Views: 3038

Answers (1)

basarat
basarat

Reputation: 276105

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 e.g 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 e.g. https://basarat.gitbook.io/typescript/main-1/typed-event

Upvotes: 6

Related Questions