Logging with Node.js
Effective logging can help you understand what is going on in an application. Logs can help triage causes of crashes or failures retrospectively by helping you to see what was happening in your application prior to the crash or failure.
Logging can also be used to help collate data. As an example, if you log all accesses to endpoints on your web application, you could collate all the request logs to determine what the most visited endpoints are.
In this recipe, we will look at logging with pino
, a JSON-based logger. In the There's more section, we'll look at the alternative Morgan and Winston loggers.
Getting ready
- First, we'll create a new directory named
express-pino-app
, initialize our project, and then install theexpress
module:$ mkdir express-pino-app $ cd express-pino-app $ npm init --yes $ npm install express
- Now, we'll create a file for our server named
server.js
:$ touch server.js
- Add the following content to...