syslog: use named captures and better logging

This commit is contained in:
Girish Ramakrishnan
2025-09-15 13:33:41 +02:00
parent 9137fb2b31
commit 8d32c853d5

View File

@@ -20,22 +20,22 @@ let gServer = null;
// example: <34>1 2023-09-07T14:33:22Z myhost myapp pid msgid [exampleSDID@32473 iut="3" eventSource="Application"] An example message
// the structured data can be "-" when missing
function parseRFC5424Message(rawMessage) {
const syslogRegex = /^<(\d+)>(\d+) (\S+) (\S+) (\S+) (\S+) (\S+) (?:\[(.*?)\]|-)?(.*)$/s; // /s means .* will match newline . (?: is non-capturing group
const syslogRegex = /^<(?<priority>\d+)>(?<version>\d+) (?<timestamp>\S+) (?<hostname>\S+) (?<appName>\S+) (?<procId>\S+) (?<msgId>\S+) (?:\[(?<structuredData>.*?)\]|-)(?<message>.*)$/s; // /s means .* will match newline . (?: is non-capturing group
const match = rawMessage.match(syslogRegex);
if (!match) return null;
const [, pri, version, timestamp, hostname, appName, procId, msgId, structuredData, message] = match;
const { priority, version, timestamp, hostname, appName, procId, msgId, structuredData, message } = match.groups;
return {
pri: parseInt(pri, 10), // priority
pri: parseInt(priority, 10), // priority
version: parseInt(version, 10), // version
timestamp, // timestamp
hostname, // hostname
appName, // app name
procId, // process ID
msgId, // message ID
structuredData: structuredData ? structuredData : null, // structured data (if present)
structuredData: structuredData || null, // structured data (if present)
message // message
};
}
@@ -56,8 +56,8 @@ async function start() {
const msg = data.toString('utf8').trim(); // strip any trailing empty new lines
for (const line of msg.split('\n')) { // empirically, multiple messages can arrive in a single packet
const info = parseRFC5424Message(line);
if (!info) return debug('Unable to parse:', msg);
if (!info.appName) return debug('Ignore unknown app:', msg);
if (!info) return debug(`Unable to parse: [${msg}]`);
if (!info.appName) return debug(`Ignore unknown app: [${msg}]`);
const appLogDir = path.join(paths.LOG_DIR, info.appName);