How to log to journald (systemd) via Python?

戏子无情 提交于 2019-12-18 03:17:24

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/34588421/how-to-log-to-journald-systemd-via-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!