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')
Basic Log Viewing. To see the logs that the journald daemon has collected, use the journalctl command. When used alone, every journal entry that is in the system will be displayed within a pager (usually less ) for you to browse.
Logs collected by systemd can be viewed by using journalctl. The journal is implemented with the journald daemon and it retrieves messages from the kernel, systemd services, and other sources. These logs are gathered in a central location, which makes it easy to review.
systemd-journald is a system service that collects and stores logging data. It creates and maintains structured, indexed journals based on logging information that is received from a variety of sources: Kernel log messages, via kmsg. Simple system log messages, via the libc syslog(3) call.
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")
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")
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With