public
Created

Use connect-logger to log to a database

  • Download Gist
connect-db-logger.js
JavaScript
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
// use like this
// var logger = require('connect-db-logger')
// app.use(logger.db("AppName"))
// RequestLog is super simple, but I don't provide it here
 
var express = require('express')
var logger = express.logger
var RequestLog = require('reports/model/RequestLog')
express.logger.token('route', function(req, res){
return req.route.path;
})
 
exports.db = function(appName, out) {
 
appName = appName || "api"
if (typeof out === "undefined") out = process.stdout
var format = ":method|appName|:url|:route:|:response-time"
var fmt = compile(logger.default) // default logger format
return function(req, res, next) {
logger({
buffer: true
, format: format
, stream: { write: dbLogger(out)}
})(req, res, next)
var line = fmt(logger, req, res)
if (null == line) return;
out.write(line + '\n', 'ascii');
}
 
function dbLogger(out) {
return function(string, encoding) {
var reqs = string.split("\n")
var len = reqs.length - 1
var arr = []
for (var i = 0; i < len; i++) {
arr = reqs[i].replace("appName", appName).split("|")
RequestLog.saveLog.apply(RequestLog, arr)
}
}
}
}
 
function compile(fmt) {
fmt = fmt.replace(/"/g, '\\"');
var js = ' return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg){
return '"\n + (tokens["' + name + '"](req, res, "' + arg + '") || "-") + "';
}) + '";'
return new Function('tokens, req, res', js);
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.