forked from pelias/api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccess_log.js
58 lines (47 loc) · 1.44 KB
/
access_log.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Create a middleware that prints access logs via pelias-logger.
*/
var url = require( 'url' );
var _ = require( 'lodash' );
var morgan = require( 'morgan' );
var through = require( 'through2' );
var peliasLogger = require( 'pelias-logger' ).get( 'api' );
var logging = require( '../helper/logging' );
function customRemoteAddr(req, res) {
if (logging.isDNT(req)) {
return '[IP removed]';
} else {
// from morgan default implementation
return req.ip ||
req._remoteAddress ||
(req.connection && req.connection.remoteAddress) ||
undefined;
}
}
function customURL(req, res) {
var parsedUrl = _.cloneDeep(req._parsedUrl);
parsedUrl.query = _.cloneDeep(req.query);
if (logging.isDNT(req)) {
// strip out sensitive fields in the query object
parsedUrl.query = logging.removeFields(parsedUrl.query);
// search will override the query object when formatting the url
// see https://nodejs.org/api/all.html#all_url_format_urlobj
delete parsedUrl.search;
}
return url.format(parsedUrl);
}
function createAccessLogger( logFormat ){
morgan.token('remote-addr', customRemoteAddr);
morgan.token('url', customURL);
return morgan( logFormat, {
stream: through( function write( ln, _, next ){
peliasLogger.info( ln.toString().trim() );
next();
})
});
}
module.exports = {
customRemoteAddr: customRemoteAddr,
customURL: customURL,
createAccessLogger: createAccessLogger
};