Merge pull request #278 from cfogelberg/custom-connect-tokens

Custom connect tokens
This commit is contained in:
Gareth Jones 2015-03-12 10:02:24 +11:00
commit 4a217afc37
3 changed files with 126 additions and 57 deletions

View File

@ -1,5 +1,6 @@
"use strict";
var levels = require("./levels");
var _ = require('underscore');
var DEFAULT_FORMAT = ':remote-addr - -' +
' ":method :url HTTP/:http-version"' +
' :status :content-length ":referrer"' +
@ -88,11 +89,12 @@ function getLogger(logger4js, options) {
if(res.statusCode >= 400) level = levels.ERROR;
}
if (thislogger.isLevelEnabled(level)) {
var combined_tokens = assemble_tokens(req, res, options.tokens || []);
if (typeof fmt === 'function') {
var line = fmt(req, res, function(str){ return format(str, req, res); });
var line = fmt(req, res, function(str){ return format(str, combined_tokens); });
if (line) thislogger.log(level, line);
} else {
thislogger.log(level, format(fmt, req, res));
thislogger.log(level, format(fmt, combined_tokens));
}
}
});
@ -103,6 +105,52 @@ function getLogger(logger4js, options) {
};
}
/**
* Adds custom {token, replacement} objects to defaults, overwriting the defaults if any tokens clash
*
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @param {Array} custom_tokens [{ token: string-or-regexp, replacement: string-or-replace-function }]
* @return {Array}
*/
function assemble_tokens(req, res, custom_tokens) {
var array_unique_tokens = function(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i].token == a[j].token) { // not === because token can be regexp object
a.splice(j--, 1);
}
}
}
return a;
};
var default_tokens = [];
default_tokens.push({ token: ':url', replacement: req.originalUrl });
default_tokens.push({ token: ':method', replacement: req.method });
default_tokens.push({ token: ':status', replacement: res.__statusCode || res.statusCode });
default_tokens.push({ token: ':response-time', replacement: res.responseTime });
default_tokens.push({ token: ':date', replacement: new Date().toUTCString() });
default_tokens.push({ token: ':referrer', replacement: req.headers.referer || req.headers.referrer || '' });
default_tokens.push({ token: ':http-version', replacement: req.httpVersionMajor + '.' + req.httpVersionMinor });
default_tokens.push({ token: ':remote-addr', replacement: req.ip || req._remoteAddress ||
(req.socket && (req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress))) });
default_tokens.push({ token: ':user-agent', replacement: req.headers['user-agent'] });
default_tokens.push({ token: ':content-length', replacement: (res._headers && res._headers['content-length']) ||
(res.__headers && res.__headers['Content-Length']) || '-' });
default_tokens.push({ token: /:req\[([^\]]+)\]/g, replacement: function(_, field) {
return req.headers[field.toLowerCase()];
} });
default_tokens.push({ token: /:res\[([^\]]+)\]/g, replacement: function(_, field) {
return res._headers ?
(res._headers[field.toLowerCase()] || res.__headers[field])
: (res.__headers && res.__headers[field]);
} });
return array_unique_tokens(custom_tokens.concat(default_tokens));
};
/**
* Return formatted log line.
*
@ -113,33 +161,10 @@ function getLogger(logger4js, options) {
* @api private
*/
function format(str, req, res) {
return str
.replace(':url', req.originalUrl)
.replace(':method', req.method)
.replace(':status', res.__statusCode || res.statusCode)
.replace(':response-time', res.responseTime)
.replace(':date', new Date().toUTCString())
.replace(':referrer', req.headers.referer || req.headers.referrer || '')
.replace(':http-version', req.httpVersionMajor + '.' + req.httpVersionMinor)
.replace(
':remote-addr', req.ip || req._remoteAddress || (
req.socket &&
(req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress))
))
.replace(':user-agent', req.headers['user-agent'] || '')
.replace(
':content-length',
(res._headers && res._headers['content-length']) ||
(res.__headers && res.__headers['Content-Length']) ||
'-'
)
.replace(/:req\[([^\]]+)\]/g, function(_, field){ return req.headers[field.toLowerCase()]; })
.replace(/:res\[([^\]]+)\]/g, function(_, field){
return res._headers ?
(res._headers[field.toLowerCase()] || res.__headers[field])
: (res.__headers && res.__headers[field]);
});
function format(str, tokens) {
return _.reduce(tokens, function(current_string, token) {
return current_string.replace(token.token, token.replacement);
}, str);
}
/**

View File

@ -31,7 +31,8 @@
"dependencies": {
"async": "~0.2.0",
"readable-stream": "~1.0.2",
"semver": "~1.1.4"
"semver": "~1.1.4",
"underscore": "1.8.2"
},
"devDependencies": {
"vows": "0.7.0",

View File

@ -246,7 +246,50 @@ vows.describe('log4js connect logger').addBatch({
'should output the response header': function(messages) {
assert.equal(messages[0].message, 'application/cheese');
}
}
},
'log events with custom token' : {
topic: function(clm) {
var ml = new MockLogger();
var cb = this.callback;
ml.level = levels.INFO;
var cl = clm.connectLogger(ml, { level: levels.INFO, format: ':method :url :custom_string', tokens: [{
token: ':custom_string', replacement: 'fooBAR'
}] } );
request(cl, 'GET', 'http://url', 200);
setTimeout(function() {
cb(null, ml.messages);
},10);
},
'check message': function(messages) {
assert.isArray(messages);
assert.equal(messages.length, 1);
assert.ok(levels.INFO.isEqualTo(messages[0].level));
assert.equal(messages[0].message, 'GET http://url fooBAR');
}
},
'log events with custom override token' : {
topic: function(clm) {
var ml = new MockLogger();
var cb = this.callback;
ml.level = levels.INFO;
var cl = clm.connectLogger(ml, { level: levels.INFO, format: ':method :url :date', tokens: [{
token: ':date', replacement: "20150310"
}] } );
request(cl, 'GET', 'http://url', 200);
setTimeout(function() {
cb(null, ml.messages);
},10);
},
'check message': function(messages) {
assert.isArray(messages);
assert.equal(messages.length, 1);
assert.ok(levels.INFO.isEqualTo(messages[0].level));
assert.equal(messages[0].message, 'GET http://url 20150310');
}
}
}
}).export(module);