├── .gitignore ├── .travis.yml ├── .eslintrc ├── .jscsrc ├── test ├── environment.js └── unit │ └── logging-test.js ├── CONTRIBUTING.md ├── NOTICE ├── package.json ├── lib └── logging.js ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/ 3 | report/ 4 | site/ 5 | .idea/ 6 | .DS_Store 7 | *.log 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "0.10" 4 | - "0.12" 5 | script: "npm run travis" 6 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "node": true 4 | }, 5 | "rules": { 6 | "no-use-before-define": [2, "nofunc"], //latedef in jshint 7 | "quotes": [2, "single"], 8 | "no-underscore-dangle": 0, 9 | "new-cap": [1, {"capIsNew": false}] 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.jscsrc: -------------------------------------------------------------------------------- 1 | { 2 | "preset": "google", 3 | "maximumLineLength": 120, 4 | "disallowSpacesInCallExpression": true, 5 | "validateJSDoc": null, 6 | "disallowMultipleVarDecl": null, 7 | "requireSpacesInNamedFunctionExpression": { 8 | "beforeOpeningCurlyBrace": true 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /test/environment.js: -------------------------------------------------------------------------------- 1 | var sinon = require ('sinon'), 2 | chai = require ('chai'), 3 | sinonChai = require('sinon-chai'); 4 | 5 | chai.use(sinonChai); 6 | 7 | global.expect = chai.expect; 8 | 9 | beforeEach(function(){ 10 | global.sinon = sinon.sandbox.create(); 11 | }); 12 | 13 | afterEach(function(){ 14 | global.sinon.restore(); 15 | }); 16 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | 1. Make a fork 4 | 5 | 2. Test the code! 6 | ```sh 7 | npm run test 8 | ``` 9 | 10 | 3. Check your coverage! 11 | ```sh 12 | npm run coverage 13 | ``` 14 | 15 | 4. Lint your code! 16 | ```sh 17 | npm run lint 18 | ``` 19 | 20 | 5. Try to squash your commits (optional) 21 | 22 | 6. Make a PR to the develop branch 23 | 24 | 7. Thanks a lot! 25 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2014,2015 Telefónica I+D 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-logging", 3 | "description": "Express middleware to log each request and response", 4 | "version": "1.1.1", 5 | "license": "Apache-2.0", 6 | "author": { 7 | "name": "Jorge Lorenzo Gallardo", 8 | "email": "jorge.lorenzogallardo@telefonica.com" 9 | }, 10 | "contributors": [ 11 | "Juan Antonio Hernando Labajo ", 12 | "Guido García Bernardo " 13 | ], 14 | "repository": { 15 | "type": "git", 16 | "url": "git@github.com:telefonica/node-express-logging.git" 17 | }, 18 | "main": "lib/logging", 19 | "engines": { 20 | "node": ">= 0.10.26" 21 | }, 22 | "scripts": { 23 | "test": "mocha -R spec test/environment.js test/unit/*-test.js", 24 | "coverage": "istanbul cover ./node_modules/mocha/bin/_mocha -- -R dot test/environment.js test/unit/*-test.js", 25 | "lint": "jscs lib && eslint lib", 26 | "prepublish": "npm run test && npm run lint", 27 | "travis": "istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec test/environment.js test/*-test.js && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage" 28 | }, 29 | "devDependencies": { 30 | "chai": "^3.0.0", 31 | "coveralls": "^2.11.2", 32 | "istanbul": "^0.3.16", 33 | "mocha": "^2.2.5", 34 | "proxyquire": "^1.5.0", 35 | "should": "^7.0.1", 36 | "sinon": "~1.15.3", 37 | "sinon-chai": "^2.8.0", 38 | "supertest": "^1.0.1", 39 | "xunit-file": "^0.0.4", 40 | "jscs": "^1.13.1", 41 | "eslint": "^0.23.0" 42 | }, 43 | "dependencies": { 44 | "on-headers": "^1.0.0" 45 | }, 46 | "keywords": [ 47 | "logging", 48 | "express", 49 | "middleware" 50 | ] 51 | } 52 | -------------------------------------------------------------------------------- /lib/logging.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | 'use strict'; 19 | 20 | var onHeaders = require('on-headers'); 21 | 22 | /** 23 | * Express middleware to log the request and response. 24 | * 25 | * @param {Object} logger 26 | * Logger. 27 | * @param {Object} opts 28 | * Object with optional arguments including: 29 | * - blacklist: Array of URL paths to be ignored (e.g. paths for static content) 30 | * - policy: Policy to generate the log entry in the logger. Possible values: 31 | * - message. Only message. Params are included into the message. 32 | * - params. Logger receives an object with the params, and the message. 33 | * @return {Function(req, res, next)} Express middleware. 34 | */ 35 | module.exports = function(logger, opts) { 36 | 37 | var blacklist = opts && opts.blacklist || []; 38 | var policy = opts && opts.policy; 39 | 40 | /** 41 | * Return the client address from the last IP address in X-Forwarded-For HTTP header. If not possible to 42 | * obtain it from X-Forwarded-For header, then return req.ip (however, this value typically is the load 43 | * balancer IP address and it does not provide any valuable information). 44 | * 45 | * @param {Object} req 46 | * Express request 47 | * @return {String} 48 | * Client IP address 49 | */ 50 | function getClientIp(req) { 51 | var xff = req.get('x-forwarded-for'); 52 | if (xff) { 53 | var ips = xff.split(',').map(function onIp(ip) { 54 | return ip.trim(); 55 | }); 56 | var ip = ips[ips.length - 1]; 57 | if (ip) { 58 | return ip; 59 | } 60 | } 61 | return req.ip; 62 | } 63 | 64 | /** 65 | * Check if the request URL starts with any of the blacklist paths. 66 | * 67 | * @param {String} url 68 | * Request url 69 | * @return {Boolean} 70 | * True if the request URL is included in the blacklist. 71 | */ 72 | function isUrlBlackedListed(url) { 73 | return blacklist.some(function(blackListUrl) { 74 | return url.indexOf(blackListUrl) === 0; 75 | }); 76 | } 77 | 78 | return function loggingMiddleware(req, res, next) { 79 | if (!isUrlBlackedListed(req.originalUrl)) { 80 | var startTime = Date.now(); 81 | if (policy === 'params') { 82 | var requestParams = { 83 | requestClientIp: getClientIp(req), 84 | requestMethod: req.method, 85 | requestUrl: req.originalUrl 86 | }; 87 | logger.info(requestParams, 'Request: %s %s', req.method, req.originalUrl); 88 | } else { 89 | logger.info('Request from %s: %s %s', getClientIp(req), req.method, req.originalUrl); 90 | } 91 | 92 | onHeaders(res, function onResponse() { 93 | var duration = Date.now() - startTime; 94 | var location = res.get('location'); 95 | if (policy === 'params') { 96 | var responseParams = { 97 | responseStatusCode: res.statusCode, 98 | responseDuration: duration, 99 | responseLocation: location 100 | }; 101 | logger.info(responseParams, 'Response with status %d', res.statusCode); 102 | } else { 103 | if (location) { 104 | logger.info('Response with status %d in %d ms. Location: %s', res.statusCode, duration, location); 105 | } else { 106 | logger.info('Response with status %d in %d ms.', res.statusCode, duration); 107 | } 108 | } 109 | }); 110 | } 111 | 112 | next(); 113 | }; 114 | 115 | }; 116 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # express-logging 2 | 3 | Express middleware to log, using a configurable logger, each request and response. 4 | 5 | [![npm version](https://badge.fury.io/js/express-logging.svg)](http://badge.fury.io/js/express-logging) 6 | [![Build Status](https://travis-ci.org/telefonica/node-express-logging.svg)](https://travis-ci.org/telefonica/node-express-logging) 7 | [![Coverage Status](https://img.shields.io/coveralls/telefonica/node-express-logging.svg)](https://coveralls.io/r/telefonica/node-express-logging) 8 | 9 | ## Installation 10 | 11 | ```bash 12 | npm install express-logging 13 | ``` 14 | 15 | ## Basic usage 16 | 17 | ```js 18 | var express = require('express'), 19 | expressLogging = require('express-logging'), 20 | logger = require('logops'); 21 | 22 | var app = express(); 23 | app.use(expressLogging(logger)); 24 | 25 | app.listen(3000); 26 | ``` 27 | 28 | ## Extended usage with options 29 | 30 | An optional argument `options` can customize enhanced aspects for the logging. This argument is an object with the following elements: 31 | 32 | - `blacklist` is available to prevent some resources from being logged (for example, static resources). This argument is an array of strings. If the URL path starts with any of the elements of the blacklist array, then the logging of this request/response is ignored. 33 | - `policy` is a string to customize how the info is logged. It supports two values: `message` or `params`. The former serializes all the log entry into a single string message. The latter passes to the logger an object with the log entry parameters and a second argument with the message; this policy is useful in order to process these parameters by systems like logstash. The default value is `message`. 34 | 35 | The following example would ignore any resource available at either `/images` or `/html`. It also activates the logging policy `params`. 36 | 37 | ```js 38 | var blacklist = ['/images', '/html']; 39 | app.use(expressLogging(logger, {blacklist: blacklist, policy: 'params'})); 40 | ``` 41 | 42 | ## Logs 43 | 44 | ### Logging with default policy **message** 45 | 46 | The request is logged with: 47 | 48 | ```js 49 | logger.info('Request from %s: %s %s', clientIpAddress, requestMethod, requestUrl); 50 | ``` 51 | 52 | A response without `Location` header is logged with: 53 | 54 | ```js 55 | logger.info('Response with status %d in %d ms.', responseStatusCode, duration); 56 | ``` 57 | 58 | A response with `Location` header is logged with: 59 | 60 | ```js 61 | logger.info('Response with status %d in %d ms. Location: %s', responseStatusCode, duration, locationHeader); 62 | ``` 63 | 64 | Both response log entries include the `duration` of the whole transaction (between receiving the request until replying with the response). 65 | 66 | ### Logging with policy **params** 67 | 68 | The request is logged with: 69 | 70 | ```js 71 | var params = {requestClientIp: requestClientIp, requestMethod: requestMethod, requestUrl: requestUrl}; 72 | logger.info(params, 'Request from %s: %s', requestMethod, requestUrl); 73 | ``` 74 | 75 | A response without `Location` header is logged with: 76 | 77 | ```js 78 | var params = {responseStatusCode: responseStatusCode, responseDuration: duration}; 79 | logger.info(params, 'Response with status %d', responseStatusCode); 80 | ``` 81 | 82 | A response with `Location` header is logged with: 83 | 84 | ```js 85 | var params = {responseStatusCode: responseStatusCode, responseDuration: duration, responseLocation: locationHeader}; 86 | logger.info(params, 'Response with status %d', responseStatusCode); 87 | ``` 88 | 89 | Both response log entries include the `duration` of the whole transaction (between receiving the request until replying with the response). 90 | 91 | ## License 92 | 93 | Copyright 2015, 2016 [Telefónica Investigación y Desarrollo, S.A.U](http://www.tid.es) 94 | 95 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 96 | 97 | http://www.apache.org/licenses/LICENSE-2.0 98 | 99 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 100 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | -------------------------------------------------------------------------------- /test/unit/logging-test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var proxyquire = require('proxyquire'), 4 | sinon = require('sinon'); 5 | 6 | describe('Logging Middleware Tests', function() { 7 | 8 | var loggingMiddleware, 9 | loggerSpy; 10 | 11 | beforeEach(function() { 12 | var loggerMock = { 13 | info: function() {} 14 | }; 15 | loggerSpy = sinon.spy(loggerMock, 'info'); 16 | 17 | var onHeadersMock = function(res, cb) { 18 | cb(); 19 | }; 20 | 21 | var LoggingMiddleware = proxyquire('../../lib/logging', { 22 | 'on-headers': onHeadersMock 23 | }); 24 | loggingMiddleware = new LoggingMiddleware(loggerMock); 25 | }); 26 | 27 | it('should log the request and response', function() { 28 | var req = { 29 | method: 'GET', 30 | ip: '10.128.201.134', 31 | originalUrl: '/test?jwt=xxx', 32 | get: function() { 33 | return null; 34 | } 35 | }; 36 | var res = { 37 | statusCode: 200, 38 | get: function() { 39 | return null; 40 | } 41 | }; 42 | 43 | loggingMiddleware(req, res, function() { 44 | expect(loggerSpy.calledTwice).to.be.true; 45 | expect(loggerSpy.getCall(0).args).to.be.deep.equal([ 46 | 'Request from %s: %s %s', 47 | '10.128.201.134', 48 | 'GET', 49 | '/test?jwt=xxx']); 50 | expect(loggerSpy.getCall(1).args[0]).to.be.equal('Response with status %d in %d ms.'); 51 | expect(loggerSpy.getCall(1).args[1]).to.be.equal(200); 52 | }); 53 | }); 54 | 55 | it('should log the request and response with location header', function() { 56 | var req = { 57 | method: 'GET', 58 | ip: '10.128.201.134', 59 | originalUrl: '/test?jwt=xxx', 60 | get: function() { 61 | return null; 62 | } 63 | }; 64 | var res = { 65 | statusCode: 302, 66 | get: function(headerName) { 67 | if (headerName === 'location') { 68 | return 'http://localhost:9000/location'; 69 | } else { 70 | return null; 71 | } 72 | } 73 | }; 74 | 75 | loggingMiddleware(req, res, function() { 76 | expect(loggerSpy.calledTwice).to.be.true; 77 | expect(loggerSpy.getCall(0).args).to.be.deep.equal([ 78 | 'Request from %s: %s %s', 79 | '10.128.201.134', 80 | 'GET', 81 | '/test?jwt=xxx']); 82 | expect(loggerSpy.getCall(1).args[0]).to.be.equal('Response with status %d in %d ms. Location: %s'); 83 | expect(loggerSpy.getCall(1).args[1]).to.be.equal(302); 84 | expect(loggerSpy.getCall(1).args[3]).to.be.equal('http://localhost:9000/location'); 85 | }); 86 | }); 87 | 88 | it('should log the request and response with client IP from XFF header', function() { 89 | var req = { 90 | method: 'GET', 91 | ip: '10.128.201.134', 92 | originalUrl: '/test?jwt=xxx', 93 | get: function(name) { 94 | if (name === 'x-forwarded-for') { 95 | return '1.1.1.1, 10.128.201.200'; 96 | } else { 97 | return null; 98 | } 99 | } 100 | }; 101 | var res = { 102 | statusCode: 200, 103 | get: function() { 104 | return null; 105 | } 106 | }; 107 | 108 | loggingMiddleware(req, res, function() { 109 | expect(loggerSpy.calledTwice).to.be.true; 110 | expect(loggerSpy.getCall(0).args).to.be.deep.equal([ 111 | 'Request from %s: %s %s', 112 | '10.128.201.200', 113 | 'GET', 114 | '/test?jwt=xxx']); 115 | expect(loggerSpy.getCall(1).args[0]).to.be.equal('Response with status %d in %d ms.'); 116 | expect(loggerSpy.getCall(1).args[1]).to.be.equal(200); 117 | }); 118 | }); 119 | 120 | it('should log the request and response with client IP from request if invalid XFF header', function() { 121 | var req = { 122 | method: 'GET', 123 | ip: '10.128.201.134', 124 | originalUrl: '/test?jwt=xxx', 125 | get: function(name) { 126 | if (name === 'x-forwarded-for') { 127 | return '1.1.1.1, 10.128.201.200, '; 128 | } else { 129 | return null; 130 | } 131 | } 132 | }; 133 | var res = { 134 | statusCode: 200, 135 | get: function() { 136 | return null; 137 | } 138 | }; 139 | 140 | loggingMiddleware(req, res, function() { 141 | expect(loggerSpy.calledTwice).to.be.true; 142 | expect(loggerSpy.getCall(0).args).to.be.deep.equal([ 143 | 'Request from %s: %s %s', 144 | '10.128.201.134', 145 | 'GET', 146 | '/test?jwt=xxx']); 147 | expect(loggerSpy.getCall(1).args[0]).to.be.equal('Response with status %d in %d ms.'); 148 | expect(loggerSpy.getCall(1).args[1]).to.be.equal(200); 149 | }); 150 | }); 151 | 152 | }); 153 | 154 | describe('Logging Middleware Tests with params policy', function() { 155 | 156 | var loggingMiddleware, 157 | loggerSpy; 158 | 159 | beforeEach(function() { 160 | var loggerMock = { 161 | info: function() {} 162 | }; 163 | loggerSpy = sinon.spy(loggerMock, 'info'); 164 | 165 | var onHeadersMock = function(res, cb) { 166 | cb(); 167 | }; 168 | 169 | var LoggingMiddleware = proxyquire('../../lib/logging', { 170 | 'on-headers': onHeadersMock 171 | }); 172 | loggingMiddleware = new LoggingMiddleware(loggerMock, {policy: 'params'}); 173 | }); 174 | 175 | it('should log the request and response', function() { 176 | var req = { 177 | method: 'GET', 178 | ip: '10.128.201.134', 179 | originalUrl: '/test?jwt=xxx', 180 | get: function() { 181 | return null; 182 | } 183 | }; 184 | var res = { 185 | statusCode: 200, 186 | get: function() { 187 | return null; 188 | } 189 | }; 190 | 191 | loggingMiddleware(req, res, function() { 192 | expect(loggerSpy.calledTwice).to.be.true; 193 | expect(loggerSpy.getCall(0).args).to.be.deep.equal([ 194 | { 195 | requestClientIp: '10.128.201.134', 196 | requestMethod: 'GET', 197 | requestUrl: '/test?jwt=xxx' 198 | }, 199 | 'Request: %s %s', 200 | 'GET', 201 | '/test?jwt=xxx' 202 | ]); 203 | expect(loggerSpy.getCall(1).args[0].responseStatusCode).to.be.equal(200); 204 | expect(loggerSpy.getCall(1).args[0].responseLocation).not.to.be.defined; 205 | expect(loggerSpy.getCall(1).args[1]).to.be.equal('Response with status %d'); 206 | expect(loggerSpy.getCall(1).args[2]).to.be.equal(200); 207 | }); 208 | }); 209 | 210 | it('should log the request and response with location header', function() { 211 | var req = { 212 | method: 'GET', 213 | ip: '10.128.201.134', 214 | originalUrl: '/test?jwt=xxx', 215 | get: function() { 216 | return null; 217 | } 218 | }; 219 | var res = { 220 | statusCode: 302, 221 | get: function(headerName) { 222 | if (headerName === 'location') { 223 | return 'http://localhost:9000/location'; 224 | } else { 225 | return null; 226 | } 227 | } 228 | }; 229 | 230 | loggingMiddleware(req, res, function() { 231 | expect(loggerSpy.calledTwice).to.be.true; 232 | expect(loggerSpy.getCall(0).args).to.be.deep.equal([ 233 | { 234 | requestClientIp: '10.128.201.134', 235 | requestMethod: 'GET', 236 | requestUrl: '/test?jwt=xxx' 237 | }, 238 | 'Request: %s %s', 239 | 'GET', 240 | '/test?jwt=xxx' 241 | ]); 242 | expect(loggerSpy.getCall(1).args[0].responseStatusCode).to.be.equal(302); 243 | expect(loggerSpy.getCall(1).args[0].responseLocation).to.be.equal('http://localhost:9000/location'); 244 | expect(loggerSpy.getCall(1).args[1]).to.be.equal('Response with status %d'); 245 | expect(loggerSpy.getCall(1).args[2]).to.be.equal(302); 246 | }); 247 | }); 248 | 249 | it('should log the request and response with client IP from XFF header', function() { 250 | var req = { 251 | method: 'GET', 252 | ip: '10.128.201.134', 253 | originalUrl: '/test?jwt=xxx', 254 | get: function(name) { 255 | if (name === 'x-forwarded-for') { 256 | return '1.1.1.1, 10.128.201.200'; 257 | } else { 258 | return null; 259 | } 260 | } 261 | }; 262 | var res = { 263 | statusCode: 200, 264 | get: function() { 265 | return null; 266 | } 267 | }; 268 | 269 | loggingMiddleware(req, res, function() { 270 | expect(loggerSpy.calledTwice).to.be.true; 271 | expect(loggerSpy.getCall(0).args).to.be.deep.equal([ 272 | { 273 | requestClientIp: '10.128.201.200', 274 | requestMethod: 'GET', 275 | requestUrl: '/test?jwt=xxx' 276 | }, 277 | 'Request: %s %s', 278 | 'GET', 279 | '/test?jwt=xxx' 280 | ]); 281 | expect(loggerSpy.getCall(1).args[0].responseStatusCode).to.be.equal(200); 282 | expect(loggerSpy.getCall(1).args[0].responseLocation).not.to.be.defined; 283 | expect(loggerSpy.getCall(1).args[1]).to.be.equal('Response with status %d'); 284 | expect(loggerSpy.getCall(1).args[2]).to.be.equal(200); 285 | }); 286 | }); 287 | 288 | it('should log the request and response with client IP from request if invalid XFF header', function() { 289 | var req = { 290 | method: 'GET', 291 | ip: '10.128.201.134', 292 | originalUrl: '/test?jwt=xxx', 293 | get: function(name) { 294 | if (name === 'x-forwarded-for') { 295 | return '1.1.1.1, 10.128.201.200, '; 296 | } else { 297 | return null; 298 | } 299 | } 300 | }; 301 | var res = { 302 | statusCode: 200, 303 | get: function() { 304 | return null; 305 | } 306 | }; 307 | 308 | loggingMiddleware(req, res, function() { 309 | expect(loggerSpy.calledTwice).to.be.true; 310 | expect(loggerSpy.getCall(0).args).to.be.deep.equal([ 311 | { 312 | requestClientIp: '10.128.201.134', 313 | requestMethod: 'GET', 314 | requestUrl: '/test?jwt=xxx' 315 | }, 316 | 'Request: %s %s', 317 | 'GET', 318 | '/test?jwt=xxx' 319 | ]); 320 | expect(loggerSpy.getCall(1).args[0].responseStatusCode).to.be.equal(200); 321 | expect(loggerSpy.getCall(1).args[0].responseLocation).not.to.be.defined; 322 | expect(loggerSpy.getCall(1).args[1]).to.be.equal('Response with status %d'); 323 | expect(loggerSpy.getCall(1).args[2]).to.be.equal(200); 324 | }); 325 | }); 326 | 327 | }); 328 | 329 | describe('Logging Middleware Tests with blacklist', function() { 330 | 331 | var loggingMiddleware, 332 | loggerSpy; 333 | 334 | beforeEach(function() { 335 | var loggerMock = { 336 | info: function() {} 337 | }; 338 | loggerSpy = sinon.spy(loggerMock, 'info'); 339 | 340 | var onHeadersMock = function(res, cb) { 341 | cb(); 342 | }; 343 | 344 | var LoggingMiddleware = proxyquire('../../lib/logging', { 345 | 'on-headers': onHeadersMock 346 | }); 347 | loggingMiddleware = new LoggingMiddleware(loggerMock, {blacklist: ['/blacklist']}); 348 | }); 349 | 350 | it('should log the request and response', function() { 351 | var req = { 352 | method: 'GET', 353 | ip: '10.128.201.134', 354 | originalUrl: '/test?jwt=xxx', 355 | get: function() { 356 | return null; 357 | } 358 | }; 359 | var res = { 360 | statusCode: 200, 361 | get: function() { 362 | return null; 363 | } 364 | }; 365 | 366 | loggingMiddleware(req, res, function() { 367 | expect(loggerSpy.calledTwice).to.be.true; 368 | expect(loggerSpy.getCall(0).args).to.be.deep.equal([ 369 | 'Request from %s: %s %s', 370 | '10.128.201.134', 371 | 'GET', 372 | '/test?jwt=xxx']); 373 | expect(loggerSpy.getCall(1).args[0]).to.be.equal('Response with status %d in %d ms.'); 374 | expect(loggerSpy.getCall(1).args[1]).to.be.equal(200); 375 | }); 376 | }); 377 | 378 | it('should not log anything when the url path is in the blacklist', function() { 379 | var req = { 380 | method: 'GET', 381 | ip: '10.128.201.134', 382 | originalUrl: '/blacklist/test?jwt=xxx', 383 | get: function() { 384 | return null; 385 | } 386 | }; 387 | var res = { 388 | statusCode: 200, 389 | get: function() { 390 | return null; 391 | } 392 | }; 393 | 394 | loggingMiddleware(req, res, function() { 395 | expect(loggerSpy.called).to.be.false; 396 | }); 397 | }); 398 | 399 | }); 400 | --------------------------------------------------------------------------------