How to log to journald (systemd) via Python?

2019-02-09 00:43发布

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')

2条回答
对你真心纯属浪费
2楼-- · 2019-02-09 01:23

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")
查看更多
甜甜的少女心
3楼-- · 2019-02-09 01:29

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")
查看更多
登录 后发表回答