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.

324 lines
8.3 KiB

  1. # morgan
  2. [![NPM Version][npm-image]][npm-url]
  3. [![NPM Downloads][downloads-image]][downloads-url]
  4. [![Build Status][travis-image]][travis-url]
  5. [![Test Coverage][coveralls-image]][coveralls-url]
  6. [![Gratipay][gratipay-image]][gratipay-url]
  7. HTTP request logger middleware for node.js
  8. > Named after [Dexter](http://en.wikipedia.org/wiki/Dexter_Morgan), a show you should not watch until completion.
  9. ## API
  10. ```js
  11. var morgan = require('morgan')
  12. ```
  13. ### morgan(format, options)
  14. Create a new morgan logger middleware function using the given `format` and `options`.
  15. The `format` argument may be a string of a predefined name (see below for the names),
  16. a string of a format string, or a function that will produce a log entry.
  17. #### Options
  18. Morgan accepts these properties in the options object.
  19. #### immediate
  20. Write log line on request instead of response. This means that a requests will
  21. be logged even if the server crashes, _but data from the response (like the
  22. response code, content length, etc.) cannot be logged_.
  23. ##### skip
  24. Function to determine if logging is skipped, defaults to `false`. This function
  25. will be called as `skip(req, res)`.
  26. ```js
  27. // EXAMPLE: only log error responses
  28. morgan('combined', {
  29. skip: function (req, res) { return res.statusCode < 400 }
  30. })
  31. ```
  32. ##### stream
  33. Output stream for writing log lines, defaults to `process.stdout`.
  34. #### Predefined Formats
  35. There are various pre-defined formats provided:
  36. ##### combined
  37. Standard Apache combined log output.
  38. ```
  39. :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
  40. ```
  41. ##### common
  42. Standard Apache common log output.
  43. ```
  44. :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]
  45. ```
  46. ##### dev
  47. Concise output colored by response status for development use. The `:status`
  48. token will be colored red for server error codes, yellow for client error
  49. codes, cyan for redirection codes, and uncolored for all other codes.
  50. ```
  51. :method :url :status :response-time ms - :res[content-length]
  52. ```
  53. ##### short
  54. Shorter than default, also including response time.
  55. ```
  56. :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
  57. ```
  58. ##### tiny
  59. The minimal output.
  60. ```
  61. :method :url :status :res[content-length] - :response-time ms
  62. ```
  63. #### Tokens
  64. ##### Creating new tokens
  65. 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:
  66. ```js
  67. morgan.token('type', function(req, res){ return req.headers['content-type']; })
  68. ```
  69. Calling `morgan.token()` using the same name as an existing token will overwrite that token definition.
  70. ##### :date[format]
  71. The current date and time in UTC. The available formats are:
  72. - `clf` for the common log format (`"10/Oct/2000:13:55:36 +0000"`)
  73. - `iso` for the common ISO 8601 date time format (`2000-10-10T13:55:36.000Z`)
  74. - `web` for the common RFC 1123 date time format (`Tue, 10 Oct 2000 13:55:36 GMT`)
  75. If no format is given, then the default is `web`.
  76. ##### :http-version
  77. The HTTP version of the request.
  78. ##### :method
  79. The HTTP method of the request.
  80. ##### :referrer
  81. The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
  82. ##### :remote-addr
  83. The remote address of the request. This will use `req.ip`, otherwise the standard `req.connection.remoteAddress` value (socket address).
  84. ##### :remote-user
  85. The user authenticated as part of Basic auth for the request.
  86. ##### :req[header]
  87. The given `header` of the request.
  88. ##### :res[header]
  89. The given `header` of the response.
  90. ##### :response-time[digits]
  91. The time between the request coming into `morgan` and when the response
  92. headers are written, in milliseconds.
  93. The `digits` argument is a number that specifies the number of digits to
  94. include on the number, defaulting to `3`, which provides microsecond percision.
  95. ##### :status
  96. The status code of the response.
  97. If the request/response cycle completes before a response was sent to the
  98. client (for example, the TCP socket closed prematurely by a client aborting
  99. the request), then the status will be empty (displayed as `"-"` in the log).
  100. ##### :url
  101. The URL of the request. This will use `req.originalUrl` if exists, otherwise `req.url`.
  102. ##### :user-agent
  103. The contents of the User-Agent header of the request.
  104. ### morgan.compile(format)
  105. Compile a format string into a function for use by `morgan`. A format string
  106. is a string that represents a single log line and can utilize token syntax.
  107. Tokens are references by `:token-name`. If tokens accept arguments, they can
  108. be passed using `[]`, for example: `:token-name[pretty]` would pass the string
  109. `'pretty'` as an argument to the token `token-name`.
  110. Normally formats are defined using `morgan.format(name, format)`, but for certain
  111. advanced uses, this compile function is directly available.
  112. ## Examples
  113. ### express/connect
  114. Simple app that will log all request in the Apache combined format to STDOUT
  115. ```js
  116. var express = require('express')
  117. var morgan = require('morgan')
  118. var app = express()
  119. app.use(morgan('combined'))
  120. app.get('/', function (req, res) {
  121. res.send('hello, world!')
  122. })
  123. ```
  124. ### vanilla http server
  125. Simple app that will log all request in the Apache combined format to STDOUT
  126. ```js
  127. var finalhandler = require('finalhandler')
  128. var http = require('http')
  129. var morgan = require('morgan')
  130. // create "middleware"
  131. var logger = morgan('combined')
  132. http.createServer(function (req, res) {
  133. var done = finalhandler(req, res)
  134. logger(req, res, function (err) {
  135. if (err) return done(err)
  136. // respond to request
  137. res.setHeader('content-type', 'text/plain')
  138. res.end('hello, world!')
  139. })
  140. })
  141. ```
  142. ### write logs to a file
  143. #### single file
  144. Simple app that will log all requests in the Apache combined format to the file
  145. `access.log`.
  146. ```js
  147. var express = require('express')
  148. var fs = require('fs')
  149. var morgan = require('morgan')
  150. var app = express()
  151. // create a write stream (in append mode)
  152. var accessLogStream = fs.createWriteStream(__dirname + '/access.log', {flags: 'a'})
  153. // setup the logger
  154. app.use(morgan('combined', {stream: accessLogStream}))
  155. app.get('/', function (req, res) {
  156. res.send('hello, world!')
  157. })
  158. ```
  159. #### log file rotation
  160. Simple app that will log all requests in the Apache combined format to one log
  161. file per date in the `log/` directory using the
  162. [file-stream-rotator module](https://www.npmjs.com/package/file-stream-rotator).
  163. ```js
  164. var FileStreamRotator = require('file-stream-rotator')
  165. var express = require('express')
  166. var fs = require('fs')
  167. var morgan = require('morgan')
  168. var app = express()
  169. var logDirectory = __dirname + '/log'
  170. // ensure log directory exists
  171. fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
  172. // create a rotating write stream
  173. var accessLogStream = FileStreamRotator.getStream({
  174. date_format: 'YYYYMMDD',
  175. filename: logDirectory + '/access-%DATE%.log',
  176. frequency: 'daily',
  177. verbose: false
  178. })
  179. // setup the logger
  180. app.use(morgan('combined', {stream: accessLogStream}))
  181. app.get('/', function (req, res) {
  182. res.send('hello, world!')
  183. })
  184. ```
  185. ### use custom token formats
  186. Sample app that will use custom token formats. This adds an ID to all requests and displays it using the `:id` token.
  187. ```js
  188. var express = require('express')
  189. var morgan = require('morgan')
  190. var uuid = require('node-uuid')
  191. morgan.token('id', function getId(req) {
  192. return req.id
  193. })
  194. var app = express()
  195. app.use(assignId)
  196. app.use(morgan(':id :method :url :response-time'))
  197. app.get('/', function (req, res) {
  198. res.send('hello, world!')
  199. })
  200. function assignId(req, res, next) {
  201. req.id = uuid.v4()
  202. next()
  203. }
  204. ```
  205. ## License
  206. [MIT](LICENSE)
  207. [npm-image]: https://img.shields.io/npm/v/morgan.svg
  208. [npm-url]: https://npmjs.org/package/morgan
  209. [travis-image]: https://img.shields.io/travis/expressjs/morgan/master.svg
  210. [travis-url]: https://travis-ci.org/expressjs/morgan
  211. [coveralls-image]: https://img.shields.io/coveralls/expressjs/morgan/master.svg
  212. [coveralls-url]: https://coveralls.io/r/expressjs/morgan?branch=master
  213. [downloads-image]: https://img.shields.io/npm/dm/morgan.svg
  214. [downloads-url]: https://npmjs.org/package/morgan
  215. [gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg
  216. [gratipay-url]: https://www.gratipay.com/dougwilson/