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 the
npm registry. Installation is done using the
npm 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 log
line, 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 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)
.
// 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 uncolored
for 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 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.
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, the
value will be displayed as "-"
in the log.
The given header
of the response. 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.
The digits
argument is a number that specifies the number of digits to
include 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 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).
The time between the request coming into morgan
and when the response
has finished being written out to the connection, 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.
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 string
is a string that represents a single log line and can utilize token syntax.
Tokens are references by :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
.
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. 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 certain
advanced 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 file
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 log/
directory using the
rotating-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, enabling
combinations like:
Sample app that will log all requests to a file using Apache format, but error 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() }
AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
最强AI数据分析助手
小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。
像人一样思考的AI智能体
imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。
AI数字人视频创作平台
Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。
一站式AI创作平台
提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作
AI办公助手,复杂任务高效处理
AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限 于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩 、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号