You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

501 lines
9.4 KiB

  1. /*!
  2. * morgan
  3. * Copyright(c) 2010 Sencha Inc.
  4. * Copyright(c) 2011 TJ Holowaychuk
  5. * Copyright(c) 2014 Jonathan Ong
  6. * Copyright(c) 2014-2015 Douglas Christopher Wilson
  7. * MIT Licensed
  8. */
  9. 'use strict'
  10. /**
  11. * Module exports.
  12. * @public
  13. */
  14. module.exports = morgan
  15. module.exports.compile = compile
  16. module.exports.format = format
  17. module.exports.token = token
  18. /**
  19. * Module dependencies.
  20. * @private
  21. */
  22. var auth = require('basic-auth')
  23. var debug = require('debug')('morgan')
  24. var deprecate = require('depd')('morgan')
  25. var onFinished = require('on-finished')
  26. var onHeaders = require('on-headers')
  27. /**
  28. * Array of CLF month names.
  29. * @private
  30. */
  31. var clfmonth = [
  32. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  33. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  34. ]
  35. /**
  36. * Default log buffer duration.
  37. * @private
  38. */
  39. var defaultBufferDuration = 1000;
  40. /**
  41. * Create a logger middleware.
  42. *
  43. * @public
  44. * @param {String|Function} format
  45. * @param {Object} [options]
  46. * @return {Function} middleware
  47. */
  48. function morgan(format, options) {
  49. var fmt = format
  50. var opts = options || {}
  51. if (format && typeof format === 'object') {
  52. opts = format
  53. fmt = opts.format || 'default'
  54. // smart deprecation message
  55. deprecate('morgan(options): use morgan(' + (typeof fmt === 'string' ? JSON.stringify(fmt) : 'format') + ', options) instead')
  56. }
  57. if (fmt === undefined) {
  58. deprecate('undefined format: specify a format')
  59. }
  60. // output on request instead of response
  61. var immediate = opts.immediate
  62. // check if log entry should be skipped
  63. var skip = opts.skip || false
  64. // format function
  65. var formatLine = typeof fmt !== 'function'
  66. ? getFormatFunction(fmt)
  67. : fmt
  68. // stream
  69. var buffer = opts.buffer
  70. var stream = opts.stream || process.stdout
  71. // buffering support
  72. if (buffer) {
  73. deprecate('buffer option')
  74. // flush interval
  75. var interval = typeof buffer !== 'number'
  76. ? defaultBufferDuration
  77. : buffer
  78. // swap the stream
  79. stream = createBufferStream(stream, interval)
  80. }
  81. return function logger(req, res, next) {
  82. // request data
  83. req._startAt = undefined
  84. req._startTime = undefined
  85. req._remoteAddress = getip(req)
  86. // response data
  87. res._startAt = undefined
  88. res._startTime = undefined
  89. // record request start
  90. recordStartTime.call(req)
  91. function logRequest() {
  92. if (skip !== false && skip(req, res)) {
  93. debug('skip request')
  94. return
  95. }
  96. var line = formatLine(morgan, req, res)
  97. if (null == line) {
  98. debug('skip line')
  99. return
  100. }
  101. debug('log request')
  102. stream.write(line + '\n')
  103. };
  104. if (immediate) {
  105. // immediate log
  106. logRequest()
  107. } else {
  108. // record response start
  109. onHeaders(res, recordStartTime)
  110. // log when response finished
  111. onFinished(res, logRequest)
  112. }
  113. next();
  114. };
  115. }
  116. /**
  117. * Apache combined log format.
  118. */
  119. morgan.format('combined', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"')
  120. /**
  121. * Apache common log format.
  122. */
  123. morgan.format('common', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]')
  124. /**
  125. * Default format.
  126. */
  127. morgan.format('default', ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"')
  128. deprecate.property(morgan, 'default', 'default format: use combined format')
  129. /**
  130. * Short format.
  131. */
  132. morgan.format('short', ':remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms')
  133. /**
  134. * Tiny format.
  135. */
  136. morgan.format('tiny', ':method :url :status :res[content-length] - :response-time ms')
  137. /**
  138. * dev (colored)
  139. */
  140. morgan.format('dev', function developmentFormatLine(tokens, req, res) {
  141. // get the status code if response written
  142. var status = res._header
  143. ? res.statusCode
  144. : undefined
  145. // get status color
  146. var color = status >= 500 ? 31 // red
  147. : status >= 400 ? 33 // yellow
  148. : status >= 300 ? 36 // cyan
  149. : status >= 200 ? 32 // green
  150. : 0 // no color
  151. // get colored function
  152. var fn = developmentFormatLine[color]
  153. if (!fn) {
  154. // compile
  155. fn = developmentFormatLine[color] = compile('\x1b[0m:method :url \x1b['
  156. + color + 'm:status \x1b[0m:response-time ms - :res[content-length]\x1b[0m')
  157. }
  158. return fn(tokens, req, res)
  159. })
  160. /**
  161. * request url
  162. */
  163. morgan.token('url', function getUrlToken(req) {
  164. return req.originalUrl || req.url
  165. })
  166. /**
  167. * request method
  168. */
  169. morgan.token('method', function getMethodToken(req) {
  170. return req.method;
  171. });
  172. /**
  173. * response time in milliseconds
  174. */
  175. morgan.token('response-time', function getResponseTimeToken(req, res, digits) {
  176. if (!req._startAt || !res._startAt) {
  177. // missing request and/or response start time
  178. return
  179. }
  180. // calculate diff
  181. var ms = (res._startAt[0] - req._startAt[0]) * 1e3
  182. + (res._startAt[1] - req._startAt[1]) * 1e-6
  183. // return truncated value
  184. return ms.toFixed(digits === undefined ? 3 : digits)
  185. })
  186. /**
  187. * current date
  188. */
  189. morgan.token('date', function getDateToken(req, res, format) {
  190. var date = new Date()
  191. switch (format || 'web') {
  192. case 'clf':
  193. return clfdate(date)
  194. case 'iso':
  195. return date.toISOString()
  196. case 'web':
  197. return date.toUTCString()
  198. }
  199. });
  200. /**
  201. * response status code
  202. */
  203. morgan.token('status', function getStatusToken(req, res) {
  204. return res._header
  205. ? String(res.statusCode)
  206. : undefined
  207. })
  208. /**
  209. * normalized referrer
  210. */
  211. morgan.token('referrer', function getReferrerToken(req) {
  212. return req.headers['referer'] || req.headers['referrer'];
  213. });
  214. /**
  215. * remote address
  216. */
  217. morgan.token('remote-addr', getip)
  218. /**
  219. * remote user
  220. */
  221. morgan.token('remote-user', function getRemoteUserToken(req) {
  222. // parse basic credentials
  223. var credentials = auth(req)
  224. // return username
  225. return credentials
  226. ? credentials.name
  227. : undefined
  228. })
  229. /**
  230. * HTTP version
  231. */
  232. morgan.token('http-version', function getHttpVersionToken(req) {
  233. return req.httpVersionMajor + '.' + req.httpVersionMinor
  234. })
  235. /**
  236. * UA string
  237. */
  238. morgan.token('user-agent', function getUserAgentToken(req) {
  239. return req.headers['user-agent'];
  240. });
  241. /**
  242. * request header
  243. */
  244. morgan.token('req', function getRequestToken(req, res, field) {
  245. // get header
  246. var header = req.headers[field.toLowerCase()]
  247. return Array.isArray(header)
  248. ? header.join(', ')
  249. : header
  250. })
  251. /**
  252. * response header
  253. */
  254. morgan.token('res', function getResponseTime(req, res, field) {
  255. if (!res._header) {
  256. return undefined
  257. }
  258. // get header
  259. var header = res.getHeader(field)
  260. return Array.isArray(header)
  261. ? header.join(', ')
  262. : header
  263. })
  264. /**
  265. * Format a Date in the common log format.
  266. *
  267. * @private
  268. * @param {Date} dateTime
  269. * @return {string}
  270. */
  271. function clfdate(dateTime) {
  272. var date = dateTime.getUTCDate()
  273. var hour = dateTime.getUTCHours()
  274. var mins = dateTime.getUTCMinutes()
  275. var secs = dateTime.getUTCSeconds()
  276. var year = dateTime.getUTCFullYear()
  277. var month = clfmonth[dateTime.getUTCMonth()]
  278. return pad2(date) + '/' + month + '/' + year
  279. + ':' + pad2(hour) + ':' + pad2(mins) + ':' + pad2(secs)
  280. + ' +0000'
  281. }
  282. /**
  283. * Compile a format string into a function.
  284. *
  285. * @param {string} format
  286. * @return {function}
  287. * @public
  288. */
  289. function compile(format) {
  290. if (typeof format !== 'string') {
  291. throw new TypeError('argument format must be a string')
  292. }
  293. var fmt = format.replace(/"/g, '\\"')
  294. var js = ' return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg) {
  295. return '"\n + (tokens["' + name + '"](req, res, ' + String(JSON.stringify(arg)) + ') || "-") + "'
  296. }) + '";'
  297. return new Function('tokens, req, res', js)
  298. }
  299. /**
  300. * Create a basic buffering stream.
  301. *
  302. * @param {object} stream
  303. * @param {number} interval
  304. * @public
  305. */
  306. function createBufferStream(stream, interval) {
  307. var buf = []
  308. var timer = null
  309. // flush function
  310. function flush() {
  311. timer = null
  312. stream.write(buf.join(''))
  313. buf.length = 0
  314. }
  315. // write function
  316. function write(str) {
  317. if (timer === null) {
  318. timer = setTimeout(flush, interval)
  319. }
  320. buf.push(str)
  321. }
  322. // return a minimal "stream"
  323. return { write: write }
  324. }
  325. /**
  326. * Define a format with the given name.
  327. *
  328. * @param {string} name
  329. * @param {string|function} fmt
  330. * @public
  331. */
  332. function format(name, fmt) {
  333. morgan[name] = fmt
  334. return this
  335. }
  336. /**
  337. * Lookup and compile a named format function.
  338. *
  339. * @param {string} name
  340. * @return {function}
  341. * @public
  342. */
  343. function getFormatFunction(name) {
  344. // lookup format
  345. var fmt = morgan[name] || name || morgan.default
  346. // return compiled format
  347. return typeof fmt !== 'function'
  348. ? compile(fmt)
  349. : fmt
  350. }
  351. /**
  352. * Get request IP address.
  353. *
  354. * @private
  355. * @param {IncomingMessage} req
  356. * @return {string}
  357. */
  358. function getip(req) {
  359. return req.ip
  360. || req._remoteAddress
  361. || (req.connection && req.connection.remoteAddress)
  362. || undefined;
  363. }
  364. /**
  365. * Pad number to two digits.
  366. *
  367. * @private
  368. * @param {number} num
  369. * @return {string}
  370. */
  371. function pad2(num) {
  372. var str = String(num)
  373. return (str.length === 1 ? '0' : '')
  374. + str
  375. }
  376. /**
  377. * Record the start time.
  378. * @private
  379. */
  380. function recordStartTime() {
  381. this._startAt = process.hrtime()
  382. this._startTime = new Date()
  383. }
  384. /**
  385. * Define a token function with the given name,
  386. * and callback fn(req, res).
  387. *
  388. * @param {string} name
  389. * @param {function} fn
  390. * @public
  391. */
  392. function token(name, fn) {
  393. morgan[name] = fn
  394. return this
  395. }