Skip to content

Instantly share code, notes, and snippets.

@xjamundx
Created January 19, 2012 23:24
Show Gist options
  • Select an option

  • Save xjamundx/1643680 to your computer and use it in GitHub Desktop.

Select an option

Save xjamundx/1643680 to your computer and use it in GitHub Desktop.
expres js db logging on top of connect-logger
// use it as a middleware like this
app.use(logger.db('appName')) // by default logs to a db and console.log
app.use(logger.db('appName', false)) // don't log to console.log
// logger.js
var express = require('express')
var logger = express.logger
var RequestLog = require('reports/model/RequestLog')
express.logger.token('route', function(req, res) {
var route = req.route || {}
return route.path || "static" // we don't get a route for static files
})
exports.db = function(appName, out) {
appName = appName || "api"
if (typeof out === "undefined") out = process.stdout
var format = ":method||:url|:route|:response-time||appName"
var fmt = compile(logger.default) // default logger format
return function(req, res, next) {
logger({
buffer: true
, format: format
, stream: { write: dbLogger}
})(req, res, next)
if (!out) return
var line = fmt(logger, req, res)
if (null == line) return;
out.write(line + '\n', 'ascii');
}
function dbLogger(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("|")
if (arr[3] === "static") return // we only care about things with routes
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