Skip to content

Instantly share code, notes, and snippets.

@henno
Last active November 23, 2022 17:07
Show Gist options
  • Save henno/c7db81df8a6b3562b7a8becbb2adc7d3 to your computer and use it in GitHub Desktop.
Save henno/c7db81df8a6b3562b7a8becbb2adc7d3 to your computer and use it in GitHub Desktop.
const express = require('express');
const fs = require("fs");
const readline = require("readline");
const app = express();
const port = 3003;
let ip;
let userName;
// Process JSON in request body
app.use(express.json());
// Store IP
app.use(function (req, res, next) {
ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
next();
});
// Log the event to file
function log(eventName, extraData) {
// Create timestamp
const timeStamp = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
// Parse extraData to JSON and escape commas with backslash
extraData = JSON.stringify(extraData).replace(/,/g, '\\,');
// Write to file
fs.appendFile('log.txt', timeStamp + ',' + ip + ',' + userName + ',' + eventName + ',' + extraData + ' \r\n', function (err) {
if (err) throw err;
});
}
app.get('/logs', async (req, res) => {
// Log a random test event
log('testEvent', {message: 'logs,logs,logs'});
// Read the log file
const lines = [];
const lineReader = readline.createInterface({
input: fs.createReadStream('log.txt'),
crlfDelay: Infinity
});
// Parse the log file
for await (const line of lineReader) {
// Split the line into array with comma as delimiter, except when comma is escaped with backslash
const fields = line.match(/(\\.|[^,])+/g)
// Iterate over result
for (let i = 0; i < fields.length; i++) {
// Remove backslash from escaped commas
fields[i] = fields[i].replace(/\\/g, '');
}
// Add the line to the lines array
lines.push({
timestamp: fields[0],
ip: fields[1],
userName: fields[2],
eventName: fields[3],
extraData: fields[4]
});
}
// Return the lines array
return res.send(lines);
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
@henno
Copy link
Author

henno commented Nov 23, 2022

YOU MUST TAKE CARE OF SETTING THE USERNAME YOURSELF

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment