Files
cloudron-box/syslog/server.js

65 lines
1.9 KiB
JavaScript
Raw Normal View History

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'),
2023-04-14 19:31:45 +02:00
debug = require('debug')('syslog:server'),
2018-06-25 00:28:42 +02:00
dgram = require('dgram'),
fs = require('fs'),
path = require('path'),
2023-04-14 19:31:45 +02:00
parser = require('nsyslog-parser'),
util = require('util');
2018-06-25 00:28:42 +02:00
2022-01-13 16:25:43 -08:00
let server = null;
2018-06-25 00:28:42 +02:00
2023-04-14 19:31:45 +02:00
async function start(options) {
2018-06-25 00:28:42 +02:00
assert.strictEqual(typeof options, 'object');
assert.strictEqual(typeof options.port, 'number');
assert.strictEqual(typeof options.logFolder, 'string');
2023-04-14 19:31:45 +02:00
debug('==========================================');
debug(' Cloudron Syslog Daemon ');
debug('==========================================');
2018-06-25 00:28:42 +02:00
server = dgram.createSocket('udp4');
server.on('error', function (error) {
2023-04-14 19:31:45 +02:00
console.error(`socket error: ${error}`);
});
server.on('message', function (msg /*, rinfo */) {
2022-01-13 16:25:43 -08:00
const info = parser(msg.toString());
2018-06-25 00:28:42 +02:00
2023-04-14 19:31:45 +02:00
if (!info || !info.appName) return debug('Ignore unknown app log:', msg.toString());
2018-06-25 00:28:42 +02:00
// 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);
}
2023-04-14 19:31:45 +02:00
});
2018-06-25 00:28:42 +02:00
2023-04-14 19:31:45 +02:00
await util.promisify(server.bind.bind(server))(options.port); // intentional double "bind"
2018-06-25 00:28:42 +02:00
2023-04-14 19:31:45 +02:00
debug(`Listening on port ${options.port}`);
}
2018-06-25 00:28:42 +02:00
2023-04-14 19:31:45 +02:00
async function stop() {
if (!server) return;
await util.promisify(server.close.bind(server))();
2018-06-25 00:28:42 +02:00
server = null;
2023-04-14 19:31:45 +02:00
}