HTTP request logger middleware for node.jsnode.js的HTTP请求记录器中间件
Named after Dexter, a show you should not watch until completion.以Dexter的名字命名,这是一个在节目完成之前不应该看的节目。
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
var morgan = require('morgan')
Create a new morgan logger middleware function using the given 使用给定的format
and options
. format
和options
创建新的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
函数将使用三个参数tokens
、req
和res
调用,其中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
以跳过日志记录。
morgan('tiny')
morgan(':method :url :status :res[content-length] - :response-time ms')
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(' ')
})
Morgan accepts these properties in the options object.Morgan在options对象中接受这些属性。
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.这意味着即使服务器崩溃,请求也会被记录,但是来自响应的数据(如响应代码、内容长度等)无法被记录。
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 }
})
Output stream for writing log lines, defaults to 用于写入日志行的输出流,默认为process.stdout
.process.stdout
。
There are various pre-defined formats provided:提供了各种预定义格式:
Standard Apache combined log output.标准Apache组合日志输出。
:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
Standard Apache common log output.标准Apache公共日志输出。
:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]
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]
Shorter than default, also including response time.短于默认值,也包括响应时间。
:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
The minimal output.最小输出。
:method :url :status :res[content-length] - :response-time ms
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. req
和res
调用token函数,两个参数表示HTTP请求和HTTP响应。Additionally, the token can accept further arguments of it's choosing to customize behavior.此外,令牌可以接受它选择自定义行为的进一步参数。
The current date and time in UTC. The available formats are:当前日期和时间(UTC)。可用的格式有:
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
.web
。
The HTTP version of the request.请求的HTTP版本。
The HTTP method of the request.请求的HTTP方法。
The Referrer header of the request. 请求的Referer标头。This will use the standard mis-spelled Referer header if exists, otherwise Referrer.这将使用标准拼写错误的Referer标题(如果存在),否则为Referer。
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
值(套接字地址)。
The user authenticated as part of Basic auth for the request.作为请求的基本身份验证的一部分进行身份验证的用户。
The given 请求的给定header
of the request. header
。If the header is not present, the value will be displayed as 如果标头不存在,则该值将在日志中显示为"-"
in the log."-"
。
The given 响应的给定header
of the response. header
。If the header is not present, the value will be displayed as 如果标题不存在,则该值将在日志中显示为"-"
in the log."-"
。
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,提供微秒精度。
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 如果请求/响应周期在向客户端发送响应之前完成(例如,客户端中止请求时TCP套接字过早关闭),则状态将为空(在日志中显示为"-"
in the log)."-"
。
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
,提供微秒精度。
The URL of the request. 请求的URL。This will use 如果存在,则使用req.originalUrl
if exists, otherwise req.url
.req.originalUrl
,否则使用req.url
。
The contents of the User-Agent header of the request.请求的用户代理标头的内容。
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
返回的函数有三个参数tokens
、req
和res
,其中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)
定义格式,但对于某些高级用途,此编译函数直接可用。
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!')
})
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!')
})
})
Sample app that will log all requests in the Apache combined format to the file 示例应用程序将以Apache组合格式将所有请求记录到文件access.log
.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!')
})
Sample app that will log all requests in the Apache combined format to one log file per day in the 示例应用程序将使用旋转文件流模块,每天将所有Apache组合格式的请求记录到log/
directory using the rotating-file-stream module.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!')
})
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!')
})
Sample app that will use custom token formats. 将使用自定义令牌格式的示例应用程序。This adds an ID to all requests and displays it using the 这将向所有请求添加一个ID,并使用:id
token.: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()
}