[英]How to log to journald (systemd) via Python?
I would like logging.info()
to go to journald (systemd).我想要
logging.info()
到 go 到 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 个读取 journald 的模块(不是我想要的)或像这样工作的模块:
journal.send('Hello world')
python-systemd has a JournalHandler you can use with the logging framework. python-systemd有一个可以与日志框架一起使用的JournalHandler 。
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. 作为官方软件包的替代品, systemd软件包可以与python 3.6一起使用。 Its source is also on github .
它的来源也在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 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()
```
This is a solution without third party modules.这是一个没有第三方模块的解决方案。 It works fine for me and the messages show up in journald.
它对我来说很好用,并且消息显示在 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.