Merge remote-tracking branch 'syslog/master'
Merge cloudron-syslog code here
This commit is contained in:
61
syslog/server.js
Normal file
61
syslog/server.js
Normal file
@@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
|
||||
exports = module.exports = {
|
||||
start,
|
||||
stop
|
||||
};
|
||||
|
||||
const LOG_FILENAME = 'app.log';
|
||||
|
||||
const assert = require('assert'),
|
||||
dgram = require('dgram'),
|
||||
fs = require('fs'),
|
||||
path = require('path'),
|
||||
parser = require('nsyslog-parser');
|
||||
|
||||
let server = null;
|
||||
|
||||
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();
|
||||
}).on('message', function (msg /*, rinfo */) {
|
||||
const info = parser(msg.toString());
|
||||
|
||||
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 {
|
||||
fs.mkdirSync(filePath, { recursive: true });
|
||||
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();
|
||||
}
|
||||
Reference in New Issue
Block a user