We are using console.log('%O', req) here to log the entire object. console.log uses util.format under the hood that supports additionally to %O other placeholders. You can read about them in the Node.js documentation.

When you run node index.js to execute your server and navigate to http://localhost:3000 you'll notice that it will print a lot of information that we don't really need.

If you change it to console.log('%s', req) to not print the entire object we'll not get much information either.

We could write our own log function that only prints the things we care about, but let's first take a step back and talk about what we typically care about. While the message often stands in the center of our attention, in reality there's often additional info that we might need. Information such as:

Timestamp - to know when things happened

Computer/Server Name - in case you are running a distributed system

Process ID - in case you are running multiple Node processes using something like pm2

Message - an actual message with some content

Stack Trace - in case we are logging an error

Maybe some additional variables/info

Additionally, now that we know that everything goes to stdout and stderr anyways, we would probably want different log levels and the ability to configure and filter our logs by them.

We can get all of that through accessing various parts of process and writing a bunch of JavaScript but the best thing about Node.js is that we got the npm ecosystem and there are a variety of libraries already out there for us to use. A few of those are:

pino

winston

roarr

bunyan (Note that this hasn't been updated for 2 years)

I personally like pino because it's fast and has a nice ecosystem. Let's see how using pino can help us with logging. The neat thing is that there's already a express-pino-logger package that we can use to log the requests.