Node.js: How to Power Up Your Logging
Tags: node, webdev, programming, logging
Published: 2022-05-01 20:28:49

Logging is an essential part of creating, debugging, and maintaining your Node.js application. By analyzing logs you can understand what’s happening in the code to quickly identify and resolve problems and find opportunities for improvements. **When should you log**, **what makes a good log message**, and **what logging library should you use**? These questions and more we’ll answer in this post so you can power up your logging.

To instead learn about JavaScript logging see [JavaScript: How to Power Up Your Logging](https://dev.to/simeg/javascript-how-to-power-up-your-logging-542m).

## When Should I Log?
### The Right Log Level
Node.js, much like other languages, provides [different levels](https://nodejs.org/api/console.html) for your log messages. These levels have different semantic meanings and you should use them for different events.

* [Error](https://nodejs.org/api/console.html#consoleerrordata-args): Something went wrong that your application may or may not be able to recover from.
* [Warning](https://nodejs.org/api/console.html#consolewarndata-args): Suitable for runtime errors that may cause a different result, but not necessarily an error.
* [Info](https://nodejs.org/api/console.html#consoleinfodata-args): Informative generic logs. A common use is interesting application-specific runtime events, such as when an API endpoint is called.
* [Debug](https://nodejs.org/api/console.html#consoledebugdata-args): Logs that are useful for debugging purposes but not generally interesting. Usually toggled on/off with some mechanic such as environment variable when needed. Usually contains more detailed information than info.

In Node.js the API for these methods looks the same where you pass a `message` and optional `data`.

```js
// Examples

const exception = /* Some error from a third-party API */
console.error("Something went wrong", exception);

const user = { id: 99, name: "Simon", platform: "Node.js" };
console.info("/getUser called for user with ID:", user.id);
```

### Less is More?
**Log useful data only**. It’s easy to add logs but too much logging will make it hard for you to see the interesting stuff. Before adding a logline consider what’s useful and what’s not. **Cost** may also be a factor, depending on your setup. Excessive logging may add to your billing!

## What Should I Log?
The answer to this question depends on the context but there are certain practices we can apply to all log messages. Most importantly, the message should be **unique** and **descriptive**.

You may need to search for the log message in your codebase so having a unique message will point you to the correct place. If you re-use the same message for more than one log message you may need more information to determine where it came from.

And what makes a descriptive message? Again, it’s contextual, but let’s look at an example. Here, we sent a request to a server and got an error response back.

```js
Unable to parse response
```

This isn’t very descriptive. What else should we reasonably log? A more descriptive log message may look like this:

```js
Unable to parse response from URL "https://api.com" with code "500" and message "Internal error"
```

## Logging Libraries
Logging libraries help you to apply best practices and provide features you shouldn’t spend time implementing yourself. Let’s look at some!

### Winston
Perhaps the most popular Node.js logging library, [`winston`](https://github.com/winstonjs/winston) provides a simple API for logging messages to files, consoles, and other destinations. It also includes support for various logging levels, which you can use to control the amount of detail that is logged. Winston defines itself as “A logger for just about everything”.

### pino
“Very low overhead Node.js logger” is how [`pino`](https://github.com/pinojs/pino) describes itself. It claims to be 5x faster than alternatives and uses asynchronous logging which it attributes to its speed. Logs messages are buffered and then written in chunks, in comparison to blocking logging where messages are directly written to the output stream.

### Bunyan
[`bunyan`](https://github.com/trentm/node-bunyan) argues that logs should be structured and that JSON is a good format for that. It describes itself as a “simple and fast JSON logging library” and has all the features you would expect from a logging library, including serializers and support for different runtime environments including Node.js, Browserify, and Webpack.

## Conclusion
Node.js offers many options for logging, making it easy to get details of errors and other events happening in an application. These logging options can be combined to create a comprehensive logging strategy for an application. There are many choices for Node.js logging libraries and offer different features for different use-cases. You can now power up your logging!

---

_Connect with me on [Twitter](https://twitter.com/prplcode), [LinkedIn](https://linkedin.com/in/simeg), or [GitHub](https://github.com/simeg)_

_Originally published at [prplcode.dev](https://prplcode.dev)_