HTTP request logger middleware for node.js
Named after Dexter, a show you should not watch until completion.
This is a Node.js module available through thenpm registry. Installation is done using thenpm install
command:
$ npm install morgan
var morgan = require('morgan')
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 logline, or undefined
/ null
to skip logging.
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.
Write log line on request instead of response. This means that a requests willbe logged even if the server crashes, but data from the response (like theresponse code, content length, etc.) cannot be logged.
Function to determine if logging is skipped, defaults to false
. This functionwill be called as 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
.
There are various pre-defined formats provided:
Standard Apache combined log output.
:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
Standard Apache common log output.
: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 uncoloredfor information codes.
: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.This callback function is expected to return a string value. The value returned is thenavailable 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 thattoken definition.
The token function is expected to be called with the arguments req
and res
, representingthe HTTP request and HTTP response. Additionally, the token can accept further arguments ofit's choosing to customize behavior.
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
.
The HTTP version of the request.
The HTTP method of the request.
The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
The remote address of the request. This will use req.ip
, otherwise the standard req.connection.remoteAddress
value (socket address).
The user authenticated as part of Basic auth for the request.
The given header
of the request. If the header is not present, thevalue will be displayed as "-"
in the log.
The given header
of the response. If the header is not present, thevalue will be displayed as "-"
in the log.
The time between the request coming into morgan
and when the responseheaders are written, in milliseconds.
The digits
argument is a number that specifies the number of digits toinclude on the number, defaulting to 3
, which provides microsecond precision.
The status code of the response.
If the request/response cycle completes before a response was sent to theclient (for example, the TCP socket closed prematurely by a client abortingthe request), then the status will be empty (displayed as "-"
in the log).
The time between the request coming into morgan
and when the responsehas finished being written out to the connection, in milliseconds.
The digits
argument is a number that specifies the number of digits toinclude on the number, defaulting to 3
, which provides microsecond precision.
The URL of the request. This will use req.originalUrl
if exists, otherwise req.url
.
The contents of the User-Agent header of the request.
Compile a format string into a format
function for use by morgan
. A format stringis a string that represents a single log line and can utilize token syntax.Tokens are references by :token-name
. If tokens accept arguments, they canbe passed using []
, for example: :token-name[pretty]
would pass the string'pretty'
as an argument to the token token-name
.
The function returned from morgan.compile
takes three arguments tokens
, req
, andres
, where tokens
is object with all defined tokens, req
is the HTTP request andres
is the HTTP response. The function will return a string that will be the log line,or undefined
/ null
to skip logging.
Normally formats are defined using morgan.format(name, format)
, but for certainadvanced uses, this compile function is directly available.
Sample app that will log all request in the Apache combined format to 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
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 fileaccess.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 logfile per day in the log/
directory using therotating-file-stream module.
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, enablingcombinations like:
Sample app that will log all requests to a file using Apache format, buterror responses are logged to the console:
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
token.
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()
}
morgan logger morgan is a great logging tool that anyone who works with HTTP servers in Node.js should learn to use. morgan is a middleware that allows us to easily log requests, errors, and more to t
morgan // 引入morgan包 var morgan = require('morgan') 使用方法 morgan(format,options) format:(string/function)打印方式,可以是预定义打印方式的名称,或格式化字符串,或格式化入口的回调方法 使用预定义打印方式 morgan('tiny'); 使用格式化字符串 morgan(':method :url
Morgan是一个node.js关于http请求的日志中间件 安装模块 npm install morgan --save #保存到package.json的依赖列表 使用方法 在终端打印日志 ... var logger = require('morgan'); ... app.use(logger('dev')); ... 每次http请求,express实例都会输出日志,并且使用一致的格式
morgan 安装 npm install morgan -D 使用 const morgan = require('morgan') morgan(format,options) format 使用给定的format和options创建一个新的morgan中间件 format:字符串、格式化字符串、生成日志功能的函数 format函数有三个参数:tokens、req、res. tokens是
Morgan简单的express模块 一、Morgan有什么特点 由express官方团队维护 morgan配置非常简单 支持自定义日志格式 支持日志压缩 支持分文件存储 二、安装 npm install morgan --save 三、使用入门 const express=require('express'); const morgan=require('morgan'); const por
morgan是express默认的日志中间件,也可以脱离express,作为node.js的日志组件单独使用。本文由浅入深,内容主要包括: morgan使用入门例子 如何将日志保存到本地文件 核心API使用说明及例子 进阶使用:1、日志分割 2、将日志写入数据库 源码剖析:morgan的日志格式以及预编译 入门例子 首先,初始化项目。 npm install express morgan 然后,
个人总结:这篇文章讲解了Express框架中日志记录插件morgan的示例。读完这篇文章需要10分钟 摘选自网络 章节概览 morgan是express默认的日志中间件,也可以脱离express,作为node.js的日志组件单独使用。本文由浅入深,内容主要包括: morgan使用入门例子 如何将日志保存到本地文件 核心API使用说明及例子 进阶使用:1、日志分割 2、将日志写入数据库 源码剖析
Morgan是一个node.js关于http请求的日志中间件 安装模块 npm install morgan --save #保存到package.json的依赖列表 使用方法 在终端打印日志 ... var logger = require('morgan'); ... app.use(logger('dev')); ... 每次http请求,express实例都会输出日志,并且使用一致
nodejs的express框架写应用,其中用到了morgan日志模块。下面是其中的一种格式设置方式: morgan.format('combined', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":use