syslog: restructure code

This commit is contained in:
Girish Ramakrishnan
2023-04-14 19:31:45 +02:00
parent 158ba4ea0b
commit 4c475818bc
11 changed files with 65 additions and 1754 deletions

View File

@@ -8,29 +8,34 @@ exports = module.exports = {
const LOG_FILENAME = 'app.log';
const assert = require('assert'),
debug = require('debug')('syslog:server'),
dgram = require('dgram'),
fs = require('fs'),
path = require('path'),
parser = require('nsyslog-parser');
parser = require('nsyslog-parser'),
util = require('util');
let server = null;
function start(options, callback) {
async function start(options) {
assert.strictEqual(typeof options, 'object');
assert.strictEqual(typeof options.port, 'number');
assert.strictEqual(typeof options.logFolder, 'string');
assert.strictEqual(typeof callback, 'function');
debug('==========================================');
debug(' Cloudron Syslog Daemon ');
debug('==========================================');
server = dgram.createSocket('udp4');
server.on('error', function (error) {
callback(error);
}).on('listening', function () {
callback();
}).on('message', function (msg /*, rinfo */) {
console.error(`socket error: ${error}`);
});
server.on('message', function (msg /*, rinfo */) {
const info = parser(msg.toString());
if (!info || !info.appName) return console.log('Ignore unknown app log:', msg.toString());
if (!info || !info.appName) return debug('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
@@ -45,17 +50,15 @@ function start(options, callback) {
} catch (error) {
console.error(error);
}
}).bind(options.port);
});
await util.promisify(server.bind.bind(server))(options.port); // intentional double "bind"
debug(`Listening on port ${options.port}`);
}
function stop(callback) {
assert.strictEqual(typeof callback, 'function');
if (!server) return callback();
server.close();
async function stop() {
if (!server) return;
await util.promisify(server.close.bind(server))();
server = null;
callback();
}
}