简体   繁体   中英

How do I implement generic / package-agnostic logging for a Node.JS Project?

I want to add logging to my Node.JS project, so that I can view debug logs while the application runs. There are a lot of different loggers out there for JavaScript apparently, and I'm not sure which one to use. Ideally, I would like to write my code so that the logger is not part of the codebase, but instead the logging is generic and I can switch between different generic logging libraries as I see fit. How can I do this?

Do not use Pino , debug , or any other external loggers in your project if you intend for people to take a dependency on your package!

abstract-logging: a no-op logging interface for JS modules.

You can use the NPM package abstract-logging for these purposes. It implements a standard log4j logging interface of no-ops. From the readme:

This module provides an interface for modules to include so that they can support logging via an external logger that conforms to the standard Log4j interface. One such logger is Pino. This module is intended for modules that are meant to be used by other modules.

This way, when you release your package, you only have to include the small, no dependency library as a direct dependency. Libraries like Pino , debug , etc. can be included as dev-dependencies while working on the package, and when someone takes a dependency on your package they don't have to worry about having their logging library clashing with your logging library, causing all sorts of debug troubles.

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