Created
December 15, 2011 18:02
-
-
Save xjamundx/1482112 to your computer and use it in GitHub Desktop.
Use connect-logger to log to a database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment