Morgan : Http request logger middleware

更新时间:
2024-03-04
下载文档

Morgan : Http request logger middleware

Morgan is a http request logger middleware. Morgan provides some default log formats, and users can also customize the log formats. Log output by default to stdout stream, users can also define their own stream to log.

User can use the following code to import the morgan module.

var morgan = require('middleware').morgan;

Support

The following shows multer module APIs available for each permissions.

 User ModePrivilege Mode
morgan
morgan.token

Morgan Object

morgan([format[, options])

  • format {String | Function} Define log format, default: default
  • opts {Object} The following are the options that can be passed to morgan:
    • immediate {Boolean} Write log line on request instead of response. default: false
    • skip {Function} Function to determine if logging is skipped,
    • stream {Object} Output stream for writing log lines, default: stdout stream.

Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry.

The format function will be called with three arguments tokens, req, and res, where tokens is an object with all defined tokens, req is the HTTP request and res is the HTTP response. The function is expected to return a string that will be the log line, or undefined / null to skip logging.

Example

  • Using a predefined format string.
morgan('tiny');
  • Using format string of predefined tokens.
morgan(':method :url :status :res[content-length] - :response-time ms');
  • Using a custom format function.
app.use(morgan(function (tokens, req, res) {
  return [
    tokens.method(req, res),
    tokens.url(req, res),
    tokens.status(req, res),
    tokens.res(req, res, 'Content-Length'), '-',
    tokens['response-time'](req, res), 'ms'
    ].join(' ');
}));

Options Details

immediate

Write log line on request instead of response. This means that a requests will be logged even if the server crashes, but data from the response (like the response code, content length, etc.) cannot be logged.

skip

Function to determine if logging is skipped, defaults to false. This function will be called as skip(req, res). Example:

// Only log error responses
morgan('combined', {
  skip: function(req, res) { 
    return res.statusCode < 400; 
  }
});

stream

Output stream for writing log lines, default: stdout stream. The stream object has a function attribute named write. Users can define their own stream object. Example:

// user defined stream.
morgan('combined', {
  stream: {
    write: (str) => {
      console.log(str);
    }
  }
});

Predefined Formats

There are various pre-defined formats provided:

combined

Standard Apache combined log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[Content-Length] ":referrer" ":user-agent"

common

Standard Apache common log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[Content-Length]

dev

Concise output colored by response status for development use. The :status token will be colored red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for all other codes.

:method :url :status :response-time ms - :res[Content-Length]

short

Shorter than default, also including response time.

:remote-addr :remote-user :method :url HTTP/:http-version :status :res[Content-Length] - :response-time ms

tiny

The minimal output.

:method :url :status :res[Content-Length] - :response-time ms

morgan.token(name, fn)

  • name {String} Token name.
  • fn {Function} A function that return token value. The function accepts the following parameters:
    • req {Object} Http request object.
    • res {Object} Http response object.

Token can be referenced as a variable in format string. To define a token, simply invoke morgan.token() with the name and a callback function. This callback function is expected to return a string value. The value returned is then available as ":type" in this case:

morgan.token('type', function (req, res) { 
  return req.headers['Content-Type'];
});

Calling morgan.token() using the same name as an existing token will overwrite that token definition.

The token function is expected to be called with the arguments req and res, representing the HTTP request and HTTP response. Additionally, the token can accept further arguments of it's choosing to customize behavior.

Predefined Tokens

:date[format]

The current date and time in UTC. The available formats are:

  • clf for the common log format ("10/Oct/2000:13:55:36 +0000");
  • iso for the common ISO 8601 date time format (2000-10-10T13:55:36.000Z);
  • web for the common RFC 1123 date time format (Tue, 10 Oct 2000 13:55:36 GMT);

If no format is given, then the default is web.

:http-version

The HTTP version of the request.

:method

The HTTP method of the request.

:referrer

The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.

:remote-addr

The remote address of the request. This will use req.ip.

:remote-user

The user authenticated as part of Basic auth for the request.

:req[header]

The given header of the request. If the header is not present, the value will be displayed as "-" in the log.

:res[header]

The given header of the response. If the header is not present, the value will be displayed as "-" in the log.

:response-time[digits]

The time between the request coming into morgan and when the response headers are written, in milliseconds.

The digits argument is a number that specifies the number of digits to include on the number, defaulting to 3, which provides microsecond precision.

:status

The status code of the response.

If the request/response cycle completes before a response was sent to the client (for example, the TCP socket closed prematurely by a client aborting the request), then the status will be empty (displayed as "-" in the log).

:url

The URL of the request. This will use req.url.

:user-agent

The contents of the User-Agent header of the request.

Examples

Base Example

  • Simple app that will log all request in the Apache combined format to STDOUT.
var socket = require('socket');
var WebApp = require('webapp');
var iosched = require('iosched');
var morgan = require('middleware').morgan;

// Create app.
var app = WebApp.create('app', 0, socket.sockaddr(socket.INADDR_ANY, 8000));

// Log middleware.
app.use(morgan('combined'));

// Route and handle.
app.get('/', function index(req, res) {
  res.send('Hello world!');
});

// Start app.
app.start();

// Event loop.
while (true) {
  iosched.poll();
}

Write Logs To File

Simple app that will log all requests in the Apache combined format to the file access.log.

var socket = require('socket');
var WebApp = require('webapp');
var iosched = require('iosched');
var morgan = require('middleware').morgan;
var fs = require('fs');

// Create app.
var app = WebApp.create('app', 0, socket.sockaddr(socket.INADDR_ANY, 8000));

// Define user log stream.
var stream = {
  write: (str) => {
    var file = fs.open('./access.log', 'a');
    file.write(str);
    file.close();
  }
};

// Log middleware.
app.use('/', morgan('combined', { stream: stream }));

// Route and handle.
app.get('/', function index(req, res) {
  res.send('Hello world!');
});

// Start app.
app.start();

// Event loop.
while (true) {
  iosched.poll();
}

Use Custom Token Formats

Sample app that will use custom token formats. This adds an ID to all requests and displays it using the :id token.

var socket = require('socket');
var WebApp = require('webapp');
var iosched = require('iosched');
var morgan = require('middleware').morgan;

// Create app.
var app = WebApp.create('app', 0, socket.sockaddr(socket.INADDR_ANY, 8000));

// Set req id.
var gid = 1;
app.use((req, res, next) => {
  req.id = gid++;
  next();
});

// Define token.
morgan.token('id', function getId(req) {
  return req.id;
});

// Log middleware.
app.use(morgan(':id :method :url :response-time'));

// Route and handle.
app.get('/', function index(req, res) {
  res.send('Hello world!');
});

// Start app.
app.start();

// Event loop.
while (true) {
  iosched.poll();
}
文档内容是否对您有所帮助?
有帮助
没帮助