Ubuntu

看不到由 systemd 管理的程序的日誌

  • October 20, 2016

我正在使用 systemd 來管理 Ubuntu 16 上的程序。我似乎無法從程序中獲取日誌以輸出到journalctl/var/log/syslog. journald 配置是預設配置,它至少應該將所有日誌消息 < debug 轉發到 syslog。這是日記的conf:

>&gt; cat /etc/systemd/journald.conf
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.
#
# Entries in this file show the compile time defaults.
# You can change settings by editing this file.
# Defaults can be restored by simply deleting this file.
#
# See journald.conf(5) for details.

[Journal]
#Storage=auto
#Compress=yes
#Seal=yes
#SplitMode=uid
#SyncIntervalSec=5m
#RateLimitInterval=30s
#RateLimitBurst=1000
#SystemMaxUse=
#SystemKeepFree=
#SystemMaxFileSize=
#SystemMaxFiles=100
#RuntimeMaxUse=
#RuntimeKeepFree=
#RuntimeMaxFileSize=
#RuntimeMaxFiles=100
#MaxRetentionSec=
#MaxFileSec=1month
#ForwardToSyslog=yes
#ForwardToKMsg=no
#ForwardToConsole=no
#ForwardToWall=yes
#TTYPath=/dev/console
#MaxLevelStore=debug
#MaxLevelSyslog=debug
#MaxLevelKMsg=notice
#MaxLevelConsole=info
#MaxLevelWall=emerg

程序定義為:

[Unit]
Description=My Program
After=network.target

[Service]
User=vagrant
Restart=always
WorkingDirectory=/vagrant/transporter
Environment=PORT=8080
ExecStart=/usr/bin/python3.5 catcher.py

當我在程序中呼叫時,我在orprint中看不到任何輸出。看來日誌沒有命中,這是第一個問題,但我不明白如何更改配置以獲取這些。如果我從 shell 手動()執行程序,我確實會在控制台上看到列印輸出。journalctl``/var/log/syslog``journalctl``python3.5 catcher.py

我嘗試執行更改 ExecStart 以使用python3.5 -u以便不緩衝標準輸出,但這不起作用。我還嘗試將 journald.confForwardToConsole設置更改為 yes,然後重新啟動systemd-journald服務。

任何幫助,將不勝感激。

我通過使用此 stackoverflow 文章中描述的python-systemd包裝器包 解決了這個問題。這是它的要點:

import logging
from systemd.journal import JournalHandler

log = logging.getLogger('demo')
log.addHandler(JournalHandler())
log.setLevel(logging.INFO)
log.info("sent to journal")

請注意,您需要安裝python-systemd(例如apt-get install python-systemd在 Ubuntu 上)的作業系統系統包,而不是 pip 包。顯然他們是不同的。

引用自:https://serverfault.com/questions/807054