Skip to content

Commit

Permalink
Make messages RFC3164 (bsd) compliant (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
mib1185 authored Apr 20, 2024
1 parent 5157e92 commit 3191975
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
25 changes: 19 additions & 6 deletions syslog/journal2syslog.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import logging
import logging.handlers
from os import environ
import re
import socket
from systemd import journal

SYSLOG_HOST = str(environ["SYSLOG_HOST"])
SYSLOG_PORT = int(environ["SYSLOG_PORT"])
SYSLOG_PROTO = str(environ["SYSLOG_PROTO"])
HAOS_HOSTNAME = str(environ["HAOS_HOSTNAME"])

# start journal reader and seek to end of journal
jr = journal.Reader(path="/var/log/journal")
Expand All @@ -20,17 +22,28 @@
logger.setLevel(logging.NOTSET)

if SYSLOG_PROTO.lower() == "udp":
socktype=socket.SOCK_DGRAM
socktype = socket.SOCK_DGRAM
else:
socktype=socket.SOCK_STREAM
logger.addHandler(logging.handlers.SysLogHandler(address=(SYSLOG_HOST, SYSLOG_PORT), socktype=socktype))
socktype = socket.SOCK_STREAM

syslog_handler = logging.handlers.SysLogHandler(
address=(SYSLOG_HOST, SYSLOG_PORT), socktype=socktype
)
formatter = logging.Formatter(
f"%(asctime)s %(ip)s %(prog)s: %(message)s",
defaults={"ip": HAOS_HOSTNAME},
datefmt="%b %d %H:%M:%S",
)
syslog_handler.setFormatter(formatter)
logger.addHandler(syslog_handler)

# wait for new messages in journal
while True:
change = jr.wait(timeout=None)
for entry in jr:
extra = {"prog": entry.get("SYSLOG_IDENTIFIER")}
if "CONTAINER_NAME" in entry:
msg = f"{entry.get('__REALTIME_TIMESTAMP')} | {entry.get('SYSLOG_IDENTIFIER')} | {entry.get('MESSAGE')}"
msg = re.sub(r"\x1b\[\d+m", "", entry.get("MESSAGE"))
else:
msg = f"{entry.get('__REALTIME_TIMESTAMP')} | host | {entry.get('SYSLOG_IDENTIFIER')} : {entry.get('MESSAGE')}"
logger.log(level=entry.get('PRIORITY', logging.INFO), msg=msg)
msg = entry.get("MESSAGE")
logger.log(level=entry.get("PRIORITY", logging.INFO), msg=msg, extra=extra)
2 changes: 2 additions & 0 deletions syslog/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ SYSLOG_PORT=$(bashio::config 'syslog_port')
export SYSLOG_PORT
SYSLOG_PROTO=$(bashio::config 'syslog_protocol')
export SYSLOG_PROTO
HAOS_HOSTNAME=$(bashio::info.hostname)
export HAOS_HOSTNAME

# Run daemon
bashio::log.info "Starting the daemon..."
Expand Down

0 comments on commit 3191975

Please sign in to comment.