[英]How to log to journald (systemd) via Python?
我想要logging.info()
到 go 到 journald (systemd)。
到目前为止,我只找到了 python 个读取 journald 的模块(不是我想要的)或像这样工作的模块: journal.send('Hello world')
python-systemd有一个可以与日志框架一起使用的JournalHandler 。
从文档:
import logging
from systemd.journal import JournalHandler
log = logging.getLogger('demo')
log.addHandler(JournalHandler())
log.setLevel(logging.INFO)
log.info("sent to journal")
作为官方软件包的替代品, systemd软件包可以与python 3.6一起使用。 它的来源也在github上 。
实现是官方库的镜像,有一些小的改动:
import logging
from systemd import journal
log = logging.getLogger('demo')
log.addHandler(journal.JournaldLogHandler())
log.setLevel(logging.INFO)
log.info("sent to journal")
或者更简短的方法:
from systemd import journal
journal.write("Hello Lennart")
这是没有第三方模块的替代解决方案
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()
```
这是一个没有第三方模块的解决方案。 它对我来说很好用,并且消息显示在 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.