2018-06-25 00:28:42 +02:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
|
|
exports = module.exports = {
|
2022-01-13 16:25:43 -08:00
|
|
|
start,
|
|
|
|
|
stop
|
2018-06-25 00:28:42 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const LOG_FILENAME = 'app.log';
|
|
|
|
|
|
2022-01-13 16:25:43 -08:00
|
|
|
const assert = require('assert'),
|
2018-06-25 00:28:42 +02:00
|
|
|
dgram = require('dgram'),
|
|
|
|
|
fs = require('fs'),
|
|
|
|
|
path = require('path'),
|
|
|
|
|
parser = require('nsyslog-parser');
|
|
|
|
|
|
2022-01-13 16:25:43 -08:00
|
|
|
let server = null;
|
2018-06-25 00:28:42 +02:00
|
|
|
|
|
|
|
|
function start(options, callback) {
|
|
|
|
|
assert.strictEqual(typeof options, 'object');
|
|
|
|
|
assert.strictEqual(typeof options.port, 'number');
|
|
|
|
|
assert.strictEqual(typeof options.logFolder, 'string');
|
|
|
|
|
assert.strictEqual(typeof callback, 'function');
|
|
|
|
|
|
|
|
|
|
server = dgram.createSocket('udp4');
|
|
|
|
|
|
|
|
|
|
server.on('error', function (error) {
|
|
|
|
|
callback(error);
|
|
|
|
|
}).on('listening', function () {
|
|
|
|
|
callback();
|
2022-01-13 16:25:43 -08:00
|
|
|
}).on('message', function (msg /*, rinfo */) {
|
|
|
|
|
const info = parser(msg.toString());
|
2018-06-25 00:28:42 +02:00
|
|
|
|
|
|
|
|
if (!info || !info.appName) return console.log('Ignore unknown app log:', msg.toString());
|
|
|
|
|
|
|
|
|
|
// remove line breaks to avoid holes in the log file
|
|
|
|
|
// we do not ignore empty log lines, to allow gaps for potential ease of readability
|
|
|
|
|
const message = info.message.replace(/\n/g, '');
|
|
|
|
|
|
|
|
|
|
const filePath = path.join(options.logFolder, info.appName);
|
|
|
|
|
const fileName = path.join(filePath, LOG_FILENAME);
|
|
|
|
|
|
|
|
|
|
try {
|
2022-01-13 16:25:43 -08:00
|
|
|
fs.mkdirSync(filePath, { recursive: true });
|
2018-06-25 00:28:42 +02:00
|
|
|
fs.appendFileSync(fileName, info.ts.toISOString() + ' ' + message + '\n');
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error(error);
|
|
|
|
|
}
|
|
|
|
|
}).bind(options.port);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function stop(callback) {
|
|
|
|
|
assert.strictEqual(typeof callback, 'function');
|
|
|
|
|
|
|
|
|
|
if (!server) return callback();
|
|
|
|
|
|
|
|
|
|
server.close();
|
|
|
|
|
|
|
|
|
|
server = null;
|
|
|
|
|
|
|
|
|
|
callback();
|
|
|
|
|
}
|