I would like logging.info()
to go to journald (systemd).
Up to now I only found python modules which read journald (not what I want) or modules which work like this: journal.send('Hello world')
I would like logging.info()
to go to journald (systemd).
Up to now I only found python modules which read journald (not what I want) or modules which work like this: journal.send('Hello world')
python-systemd has a JournalHandler you can use with the logging framework.
From the documentation:
import logging
from systemd.journal import JournalHandler
log = logging.getLogger('demo')
log.addHandler(JournalHandler())
log.setLevel(logging.INFO)
log.info("sent to journal")
JournalHandler(SYSLOG_IDENTIFIER=<id>)
, and then <id>
is used for the unit/id field in the corresponding log entries (if you don't set this, then the file name is used by default; see the source). However, this doesn't create a <id>
unit, so journalctl -u <id>
doesn't produce any output. But you can filter the <id>
msgs with journalctl SYSLOG_IDENTIFIER=<id>
. –
Desexualize An alternative to the official package, the systemd package works with python 3.6. Its source is also on github.
The implementation is a mirror of the official lib, with some minor changes:
import logging
from systemd import journal
log = logging.getLogger('demo')
log.addHandler(journal.JournaldLogHandler())
log.setLevel(logging.INFO)
log.info("sent to journal")
or for an even shorter method:
from systemd import journal
journal.write("Hello Lennart")
log.info(message)
. Are there equivalent methods, like log.warning(message)
? –
Roller journal.write()
does not exist but journal.send("Hello Lennart")
works! –
Chastise This is a solution without third party modules. It works fine for me and the messages show up in journald.
import logging
import sys
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# this is just to make the output look nice
formatter = logging.Formatter(fmt="%(asctime)s %(name)s.%(levelname)s: %(message)s", datefmt="%Y.%m.%d %H:%M:%S")
# this logs to stdout and I think it is flushed immediately
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info('test')
sys.stderr
stream for me. –
Spense print
and it will still end up in journald. –
Hatbox This is an alternative solution without third party modules
import subprocess
data = "sent to journal"
echoCmd = ["echo", data]
sysdCat = ["systemd-cat", "-p", "info"]
echoResult = subprocess.Popen(echoCmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
sysdCatResult = subprocess.Popen(sysdCat, stdin=echoResult.stdout)
sysdCatResult.communicate()
```
© 2022 - 2024 — McMap. All rights reserved.