How to log access and errors in Express.js web server

For someone new to Express.js, something that might not come up immediately is how logging works in Express. Even worse, tutorials rarely mention of logging in Express. In Apache you have access.log and error.log, what is the equivalent in Express?

In this post I'll show you how you can have access.log and error.log for your Express web server.

By default, logging is disabled in Express. You have to do certain stuff to get logs working for your app. For access logs, we need to use the Logger middleware; for error logs we will use Forever.

If you don't have Forever installed, here is how to do it:

$ npm install forever -g

If that gives a permissin error:

$ sudo npm install forever -g

Access logging is enabled by adding the Logger middleware to your app. Then you create a Node.js writebale stream and pass it to Logger.

Error logging is enable by starting your app with Forever with the -e option.

$ forever -e error.log start app.js

If you fancy logging console.log() stuff from your code, you can also add the -o option.

$ forever -o output.log -e error.log start app.js

You may wonder if it is worth installing a module just to enable error logging. Whether you want to enable error logging or not, you most probably would need Forever anyway, find out why.

So there you go, logging enabled for your Express.js app. For the sake of neatness, you might want to keep the logs in a directory called logs instead of the root folder of your app. The choice is yours. Happy logging!