connect-logger.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /* eslint-disable no-plusplus */
  2. const levels = require("./levels");
  3. const DEFAULT_FORMAT =
  4. ":remote-addr - -" +
  5. ' ":method :url HTTP/:http-version"' +
  6. ' :status :content-length ":referrer"' +
  7. ' ":user-agent"';
  8. /**
  9. * Return request url path,
  10. * adding this function prevents the Cyclomatic Complexity,
  11. * for the assemble_tokens function at low, to pass the tests.
  12. *
  13. * @param {IncomingMessage} req
  14. * @return {string}
  15. * @api private
  16. */
  17. function getUrl(req) {
  18. return req.originalUrl || req.url;
  19. }
  20. /**
  21. * Adds custom {token, replacement} objects to defaults,
  22. * overwriting the defaults if any tokens clash
  23. *
  24. * @param {IncomingMessage} req
  25. * @param {ServerResponse} res
  26. * @param {Array} customTokens
  27. * [{ token: string-or-regexp, replacement: string-or-replace-function }]
  28. * @return {Array}
  29. */
  30. function assembleTokens(req, res, customTokens) {
  31. const arrayUniqueTokens = array => {
  32. const a = array.concat();
  33. for (let i = 0; i < a.length; ++i) {
  34. for (let j = i + 1; j < a.length; ++j) {
  35. // not === because token can be regexp object
  36. /* eslint eqeqeq:0 */
  37. if (a[i].token == a[j].token) {
  38. a.splice(j--, 1);
  39. }
  40. }
  41. }
  42. return a;
  43. };
  44. const defaultTokens = [];
  45. defaultTokens.push({ token: ":url", replacement: getUrl(req) });
  46. defaultTokens.push({ token: ":protocol", replacement: req.protocol });
  47. defaultTokens.push({ token: ":hostname", replacement: req.hostname });
  48. defaultTokens.push({ token: ":method", replacement: req.method });
  49. defaultTokens.push({
  50. token: ":status",
  51. replacement: res.__statusCode || res.statusCode
  52. });
  53. defaultTokens.push({
  54. token: ":response-time",
  55. replacement: res.responseTime
  56. });
  57. defaultTokens.push({ token: ":date", replacement: new Date().toUTCString() });
  58. defaultTokens.push({
  59. token: ":referrer",
  60. replacement: req.headers.referer || req.headers.referrer || ""
  61. });
  62. defaultTokens.push({
  63. token: ":http-version",
  64. replacement: `${req.httpVersionMajor}.${req.httpVersionMinor}`
  65. });
  66. defaultTokens.push({
  67. token: ":remote-addr",
  68. replacement:
  69. req.headers["x-forwarded-for"] ||
  70. req.ip ||
  71. req._remoteAddress ||
  72. (req.socket &&
  73. (req.socket.remoteAddress ||
  74. (req.socket.socket && req.socket.socket.remoteAddress)))
  75. });
  76. defaultTokens.push({
  77. token: ":user-agent",
  78. replacement: req.headers["user-agent"]
  79. });
  80. defaultTokens.push({
  81. token: ":content-length",
  82. replacement:
  83. res.getHeader("content-length") ||
  84. (res.__headers && res.__headers["Content-Length"]) ||
  85. "-"
  86. });
  87. defaultTokens.push({
  88. token: /:req\[([^\]]+)]/g,
  89. replacement(_, field) {
  90. return req.headers[field.toLowerCase()];
  91. }
  92. });
  93. defaultTokens.push({
  94. token: /:res\[([^\]]+)]/g,
  95. replacement(_, field) {
  96. return (
  97. res.getHeader(field.toLowerCase()) ||
  98. (res.__headers && res.__headers[field])
  99. );
  100. }
  101. });
  102. return arrayUniqueTokens(customTokens.concat(defaultTokens));
  103. }
  104. /**
  105. * Return formatted log line.
  106. *
  107. * @param {string} str
  108. * @param {Array} tokens
  109. * @return {string}
  110. * @api private
  111. */
  112. function format(str, tokens) {
  113. for (let i = 0; i < tokens.length; i++) {
  114. str = str.replace(tokens[i].token, tokens[i].replacement);
  115. }
  116. return str;
  117. }
  118. /**
  119. * Return RegExp Object about nolog
  120. *
  121. * @param {(string|Array)} nolog
  122. * @return {RegExp}
  123. * @api private
  124. *
  125. * syntax
  126. * 1. String
  127. * 1.1 "\\.gif"
  128. * NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga
  129. * LOGGING http://example.com/hoge.agif
  130. * 1.2 in "\\.gif|\\.jpg$"
  131. * NOT LOGGING http://example.com/hoge.gif and
  132. * http://example.com/hoge.gif?fuga and http://example.com/hoge.jpg?fuga
  133. * LOGGING http://example.com/hoge.agif,
  134. * http://example.com/hoge.ajpg and http://example.com/hoge.jpg?hoge
  135. * 1.3 in "\\.(gif|jpe?g|png)$"
  136. * NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.jpeg
  137. * LOGGING http://example.com/hoge.gif?uid=2 and http://example.com/hoge.jpg?pid=3
  138. * 2. RegExp
  139. * 2.1 in /\.(gif|jpe?g|png)$/
  140. * SAME AS 1.3
  141. * 3. Array
  142. * 3.1 ["\\.jpg$", "\\.png", "\\.gif"]
  143. * SAME AS "\\.jpg|\\.png|\\.gif"
  144. */
  145. function createNoLogCondition(nolog) {
  146. let regexp = null;
  147. if (nolog instanceof RegExp) {
  148. regexp = nolog;
  149. }
  150. if (typeof nolog === "string") {
  151. regexp = new RegExp(nolog);
  152. }
  153. if (Array.isArray(nolog)) {
  154. // convert to strings
  155. const regexpsAsStrings = nolog.map(reg => (reg.source ? reg.source : reg));
  156. regexp = new RegExp(regexpsAsStrings.join("|"));
  157. }
  158. return regexp;
  159. }
  160. /**
  161. * Allows users to define rules around status codes to assign them to a specific
  162. * logging level.
  163. * There are two types of rules:
  164. * - RANGE: matches a code within a certain range
  165. * E.g. { 'from': 200, 'to': 299, 'level': 'info' }
  166. * - CONTAINS: matches a code to a set of expected codes
  167. * E.g. { 'codes': [200, 203], 'level': 'debug' }
  168. * Note*: Rules are respected only in order of prescendence.
  169. *
  170. * @param {Number} statusCode
  171. * @param {Level} currentLevel
  172. * @param {Object} ruleSet
  173. * @return {Level}
  174. * @api private
  175. */
  176. function matchRules(statusCode, currentLevel, ruleSet) {
  177. let level = currentLevel;
  178. if (ruleSet) {
  179. const matchedRule = ruleSet.find(rule => {
  180. let ruleMatched = false;
  181. if (rule.from && rule.to) {
  182. ruleMatched = statusCode >= rule.from && statusCode <= rule.to;
  183. } else {
  184. ruleMatched = rule.codes.indexOf(statusCode) !== -1;
  185. }
  186. return ruleMatched;
  187. });
  188. if (matchedRule) {
  189. level = levels.getLevel(matchedRule.level, level);
  190. }
  191. }
  192. return level;
  193. }
  194. /**
  195. * Log requests with the given `options` or a `format` string.
  196. *
  197. * Options:
  198. *
  199. * - `format` Format string, see below for tokens
  200. * - `level` A log4js levels instance. Supports also 'auto'
  201. * - `nolog` A string or RegExp to exclude target logs
  202. * - `statusRules` A array of rules for setting specific logging levels base on status codes
  203. * - `context` Whether to add a response of express to the context
  204. *
  205. * Tokens:
  206. *
  207. * - `:req[header]` ex: `:req[Accept]`
  208. * - `:res[header]` ex: `:res[Content-Length]`
  209. * - `:http-version`
  210. * - `:response-time`
  211. * - `:remote-addr`
  212. * - `:date`
  213. * - `:method`
  214. * - `:url`
  215. * - `:referrer`
  216. * - `:user-agent`
  217. * - `:status`
  218. *
  219. * @return {Function}
  220. * @param logger4js
  221. * @param options
  222. * @api public
  223. */
  224. module.exports = function getLogger(logger4js, options) {
  225. /* eslint no-underscore-dangle:0 */
  226. if (typeof options === "string" || typeof options === "function") {
  227. options = { format: options };
  228. } else {
  229. options = options || {};
  230. }
  231. const thisLogger = logger4js;
  232. let level = levels.getLevel(options.level, levels.INFO);
  233. const fmt = options.format || DEFAULT_FORMAT;
  234. const nolog = createNoLogCondition(options.nolog);
  235. return (req, res, next) => {
  236. // mount safety
  237. if (req._logging) return next();
  238. // nologs
  239. if (nolog && nolog.test(req.originalUrl)) return next();
  240. if (thisLogger.isLevelEnabled(level) || options.level === "auto") {
  241. const start = new Date();
  242. const { writeHead } = res;
  243. // flag as logging
  244. req._logging = true;
  245. // proxy for statusCode.
  246. res.writeHead = (code, headers) => {
  247. res.writeHead = writeHead;
  248. res.writeHead(code, headers);
  249. res.__statusCode = code;
  250. res.__headers = headers || {};
  251. };
  252. // hook on end request to emit the log entry of the HTTP request.
  253. res.on("finish", () => {
  254. res.responseTime = new Date() - start;
  255. // status code response level handling
  256. if (res.statusCode && options.level === "auto") {
  257. level = levels.INFO;
  258. if (res.statusCode >= 300) level = levels.WARN;
  259. if (res.statusCode >= 400) level = levels.ERROR;
  260. }
  261. level = matchRules(res.statusCode, level, options.statusRules);
  262. const combinedTokens = assembleTokens(req, res, options.tokens || []);
  263. if (options.context) thisLogger.addContext("res", res);
  264. if (typeof fmt === "function") {
  265. const line = fmt(req, res, str => format(str, combinedTokens));
  266. if (line) thisLogger.log(level, line);
  267. } else {
  268. thisLogger.log(level, format(fmt, combinedTokens));
  269. }
  270. if (options.context) thisLogger.removeContext("res");
  271. });
  272. }
  273. // ensure next gets always called
  274. return next();
  275. };
  276. };