Add Basic Logging to an Express 5 App with morgan

Share this video with your friends

Send Tweet

This lesson demonstrates using the morgan library to add basic logging to an express 5 application. We also log when the app starts up by passing a second argument to the app.listen() method.

morgan

The morgan logger has a whole list of pre-defined logging formats that you can use listed on their website. You can also build your own custom format. The format we chose for this lesson dev is a short-hand for the following :method :url :status :response-time ms - :res[content-length].

Middleware

Middleware are tiny programs that inspect and manipulate incoming requests in an express application. They can run before, after, or even in-between your other routes. They are commonly used for logging, authentication, and form processing.

A thorough list of common middleware can be found on the express website here: http://expressjs.com/en/resources/middleware.html

Middleware are typically added to your application with app.use(), but can also be added added to individual routes using app.get("/", middleware, routeHandler). While not recommended, multiple middleware can be added that way: app.get("/", middleware1, middleware2, routeHandler)

While not covered in this lesson creating a middleware is easy and they have a lot in common with route handlers. Here is a simple logging middleware:

app.use(function(res, res, next) {
    console.log(req.path);
    next();
});