Express Web Application Development
上QQ阅读APP看书,第一时间看更新

Logging requests to the App

Express comes with a built-in logging module called logger, it can be a very useful tool while you are developing the app. You enable it like any other Express module:

app.use(express.logger());

Without any options, the logger middleware will log a detailed log. You can customize the details with the following tokens in the format option of the logger middleware:

And this is how you specify the log format using the tokens:

app.use(express.logger({ format: ':remote-addr :method :url' }));

After adding the logger middleware, you can see the log details in the console, when requests are made to the app:

127.0.0.1 GET /
127.0.0.1 GET /favicon.ico

By default the logger outputs the log to the console. We can make it log to a file by specifying the stream option, as shown here:

var http = require('http');
var express = require('express');
var fs = require('fs');
var app = express();

app.use(express.logger({
  format: 'tiny',
  stream: fs.createWriteStream('app.log', {'flags': 'w'})
}));

...

The logger middleware supports four predefined log formats: default, short, tiny, and dev. You can specify one of them this way:

app.use(express.logger('dev'));

If you need to quickly check some aspects of the requests that are being made, the logger middleware is the way to go.