Add Basic Logging to an Express 5 App with morgan

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 2 years ago

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();
});

Instructor: [0:00] If your app is still running, press Ctrl C to stop it and reopen your index.js file. Now add a second argument to app.listen callback function. Inside that function, type console.log app listening on port 3000.

[0:13] Save the file, close it, and restart your app. You'll now see a helpful message telling you that your app has indeed started and where to find it. Now type npm install Morgan to install Express' logging middleware. Go back inside your index.js file near the top, type import Morgan from Morgan.

[0:33] Right underneath the app instance, type app.use and pass in Morgan, which takes a single argument. For now, type in dev.

[0:42] Save the file and start the app again. Now, I'm going to move over a terminal side by side to this one so that we can hit our application and watch what the logger does. On the right hand side, you'll see the return. It returned hello. Over here on the left hand side, you'll see that the logger is saying this was a get request.

[1:02] You asked for slash. It has the status code of 200 and it took 1.985 milliseconds to respond and it was five bytes. Now on the Morgan website, there's a whole list of additional formatting options that you can pass in, including the standard Apache log format and others that may be helpful to you. I'd advise checking that out as well.