Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Event tracking Server that insert records to MySQL (express, mysql module needed)
/* Server monitor */
// require('newrelic');
var mysql = require('mysql');
var express = require('express');
var app = express();
var eventsCollection;
var sessionsCollection;
/** MySQL Settings **/
var connection = mysql.createConnection({
host : '***',
user : '***',
password : '***',
database : '***'
});
/** End MySQL Settings **/
app.get('/iphone/log_metrics.json', function(req, res) {
res.contentType('application/json');
res.json({status:'ok'});
var params = req.query;
var events = req.query.events;
delete params["events"];
if(events){
var json = JSON.parse(events);
insertEvents(json, params);
}
});
function insertEvents(events, params) {
events.forEach(function(item) {
insertEvent(item, params);
});
}
function insertEvent(item, params) {
Object.keys(params).forEach(function(key) {
if (key=='timestamp') {
if (key in item) {
item['date'] = new Date(item[key]*1000);
} else {
item['date'] = new Date(params[key]*1000);
}
}
if (!(key in item)) {
item[key] = params[key];
}
});
if(item['attributes'] !== undefined) item['attributes'] = JSON.stringify(item['attributes']);
var query = connection.query('INSERT INTO EVENTS SET ?', item, function(err, result) {
// console.log("Adding event"+item['name']);
if(err) console.log(err);
});
}
function init(){
/* connect MySQL */
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... \n\n");
var port = 8000;
app.listen(port);
console.log("Start Server on port:" + port);
} else {
console.log("Error connecting database ... \n\n");
}
});
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment