morgan

NPM Version NPM Downloads Build Status Test Coverage

HTTP request logger middleware for node.jsnode.js的HTTP请求记录器中间件

Named after Dexter, a show you should not watch until completion.Dexter的名字命名,这是一个在节目完成之前不应该看的节目。

Installation安装

This is a Node.js module available through the npm registry. 这是一个Node.js模块,可通过npm注册表获得。Installation is done using the npm install command:使用npm install命令完成安装:

$ npm install morgan

API

var morgan = require('morgan')

morgan(format, options)

Create a new morgan logger middleware function using the given format and options. 使用给定的formatoptions创建新的morgan logger中间件函数。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.format参数可以是预定义名称的字符串(名称见下文)、格式字符串的字符串或生成日志条目的函数。

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. format函数将使用三个参数tokensreqres调用,其中tokens是一个包含所有已定义令牌的对象,req是HTTP请求,res是HTTP响应。The function is expected to return a string that will be the log line, or undefined / null to skip logging.该函数应返回一个将作为日志行的字符串,或返回undefined/null以跳过日志记录。

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使用自定义格式函数

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选项

Morgan accepts these properties in the options object.Morgan在options对象中接受这些属性。

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).函数确定是否跳过日志记录,默认为false。此函数将以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, defaults to process.stdout.用于写入日志行的输出流,默认为process.stdout

Predefined Formats预定义格式

There are various pre-defined formats provided:提供了各种预定义格式:

combined

Standard Apache combined log output.标准Apache组合日志输出。

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

Standard Apache common log output.标准Apache公共日志输出。

: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 green for success codes, red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for information codes.:status标记将为绿色表示成功代码,红色表示服务器错误代码,黄色表示客户端错误代码,青色表示重定向代码,而非彩色表示信息代码。

: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

Tokens

Creating new tokens创建新令牌

To define a token, simply invoke morgan.token() with the name and a callback function. 要定义令牌,只需使用名称和回调函数调用morgan.token()This callback function is expected to return a string value. 此回调函数应返回字符串值。The value returned is then available as ":type" in this case:在这种情况下,返回的值可用作“:type”:

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.使用与现有令牌相同的名称调用morgan.token()将覆盖该令牌定义。

The token function is expected to be called with the arguments req and res, representing the HTTP request and HTTP response. 预计将使用参数reqres调用token函数,两个参数表示HTTP请求和HTTP响应。Additionally, the token can accept further arguments of it's choosing to customize behavior.此外,令牌可以接受它选择自定义行为的进一步参数。

:date[format]

The current date and time in UTC. The available formats are:当前日期和时间(UTC)。可用的格式有:

If no format is given, then the default is web.如果未提供格式,则默认为web

:http-version

The HTTP version of the request.请求的HTTP版本。

:method

The HTTP method of the request.请求的HTTP方法。

:referrer

The Referrer header of the request. 请求的Referer标头。This will use the standard mis-spelled Referer header if exists, otherwise Referrer.这将使用标准拼写错误的Referer标题(如果存在),否则为Referer。

:remote-addr

The remote address of the request. 请求的远程地址。This will use req.ip, otherwise the standard req.connection.remoteAddress value (socket address).这将使用req.ip,否则使用标准req.connection.remoteAddress值(套接字地址)。

:remote-user

The user authenticated as part of Basic auth for the request.作为请求的基本身份验证的一部分进行身份验证的用户。

:req[header]

The given header of the request. 请求的给定headerIf the header is not present, the value will be displayed as "-" in the log.如果标头不存在,则该值将在日志中显示为"-"

:res[header]

The given header of the response. 响应的给定headerIf 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.请求进入morgan与写入响应头之间的时间,以毫秒为单位。

The digits argument is a number that specifies the number of digits to include on the number, defaulting to 3, which provides microsecond precision.digits参数是一个数字,指定数字上要包含的位数,默认为3,提供微秒精度。

: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).如果请求/响应周期在向客户端发送响应之前完成(例如,客户端中止请求时TCP套接字过早关闭),则状态将为空(在日志中显示为"-"

:total-time[digits]

The time between the request coming into morgan and when the response has finished being written out to the connection, in milliseconds.从请求进入morgan到响应完成写入连接之间的时间,以毫秒为单位。

The digits argument is a number that specifies the number of digits to include on the number, defaulting to 3, which provides microsecond precision.digits参数是一个数字,指定数字上要包含的位数,默认为3,提供微秒精度。

:url

The URL of the request. 请求的URL。This will use req.originalUrl if exists, otherwise req.url.如果存在,则使用req.originalUrl,否则使用req.url

:user-agent

The contents of the User-Agent header of the request.请求的用户代理标头的内容。

morgan.compile(format)

Compile a format string into a format function for use by morgan. 将格式字符串编译为format函数以供morgan使用。A format string is a string that represents a single log line and can utilize token syntax. 格式字符串是表示单个日志行的字符串,可以利用令牌语法。Tokens are references by :token-name. 令牌是按:token-name的方式引用的。If tokens accept arguments, they can be passed using [], for example: :token-name[pretty] would pass the string 'pretty' as an argument to the token token-name.如果令牌接受参数,则可以使用[]传递参数,例如::token-name[pretty]将字符串'pretty'作为参数传递给令牌名称。

The function returned from morgan.compile takes three arguments tokens, req, and res, where tokens is object with all defined tokens, req is the HTTP request and res is the HTTP response. morgan.compile返回的函数有三个参数tokensreqres,其中tokens是包含所有已定义标记的对象,req是HTTP请求,res是HTTP响应。The function will return a string that will be the log line, or undefined / null to skip logging.函数将返回一个字符串作为日志行,或返回undefined/null以跳过日志记录。

Normally formats are defined using morgan.format(name, format), but for certain advanced uses, this compile function is directly available.通常使用morgan.format(name, format)定义格式,但对于某些高级用途,此编译函数直接可用。

Examples例子

express/connect

Sample app that will log all request in the Apache combined format to STDOUT将所有请求以Apache组合格式记录到STDOUT的示例应用程序

var express = require('express')
var morgan = require('morgan')

var app = express()

app.use(morgan('combined'))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

vanilla http server香草http服务器

Sample app that will log all request in the Apache combined format to STDOUT将所有请求以Apache组合格式记录到STDOUT的示例应用程序

var finalhandler = require('finalhandler')
var http = require('http')
var morgan = require('morgan')

// create "middleware"
var logger = morgan('combined')

http.createServer(function (req, res) {
  var done = finalhandler(req, res)
  logger(req, res, function (err) {
    if (err) return done(err)

    // respond to request
    res.setHeader('content-type', 'text/plain')
    res.end('hello, world!')
  })
})

write logs to a file将日志写入文件

single file单个文件

Sample app that will log all requests in the Apache combined format to the file access.log.示例应用程序将以Apache组合格式将所有请求记录到文件access.log中。

var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')

var app = express()

// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })

// setup the logger
app.use(morgan('combined', { stream: accessLogStream }))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

log file rotation日志文件轮转

Sample app that will log all requests in the Apache combined format to one log file per day in the log/ directory using the rotating-file-stream module.示例应用程序将使用旋转文件流模块,每天将所有Apache组合格式的请求记录到log/目录中的一个日志文件中。

var express = require('express')
var morgan = require('morgan')
var path = require('path')
var rfs = require('rotating-file-stream') // version 2.x

var app = express()

// create a rotating write stream
var accessLogStream = rfs.createStream('access.log', {
  interval: '1d', // rotate daily
  path: path.join(__dirname, 'log')
})

// setup the logger
app.use(morgan('combined', { stream: accessLogStream }))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

split / dual logging

The morgan middleware can be used as many times as needed, enabling combinations like:morgan中间件可根据需要多次使用,支持以下组合:

Sample app that will log all requests to a file using Apache format, but error responses are logged to the console:示例应用程序将使用Apache格式将所有请求记录到一个文件中,但将错误响应记录到控制台:

var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')

var app = express()

// log only 4xx and 5xx responses to console
app.use(morgan('dev', {
  skip: function (req, res) { return res.statusCode < 400 }
}))

// log all requests to access.log
app.use(morgan('common', {
  stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
}))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

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.这将向所有请求添加一个ID,并使用:id标记显示该ID。

var express = require('express')
var morgan = require('morgan')
var uuid = require('node-uuid')

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

var app = express()

app.use(assignId)
app.use(morgan(':id :method :url :response-time'))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

function assignId (req, res, next) {
  req.id = uuid.v4()
  next()
}

License

MIT