关于日志记录:将Python Systemd输出记录到日志文件

Log Python Systemd output to log file

我将python脚本作为systemd服务运行,它在以下.service文件中定义:

1
2
3
4
5
6
7
8
9
10
[Unit]
Description=MyService
After=multi-user.target

[Service]
Type=idle
ExecStart=/usr/bin/python3 /home/username/projects/website_notifier/run_service.py

[Install]
After=multi-user.target

然后,在我的run_service.py文件中,使用日志记录模块记录输出:

1
2
3
4
import logging

logging.basicConfig(filename=settings['log_file_name'], level=logging.INFO)
logging.info("Starting notifier service at" + str(datetime.utcnow()))

问题是,当我运行通过systemctl启动文件时,此信息未记录到我的日志文件中

现在,我知道通常systemd可以将输出输出到journalctl,我不希望这样。 我希望能够通过另一个没有管理员权限运行的脚本访问此日志。

我怎样才能做到这一点?


首先检查您的服务是否正在运行:systemctl status MyService应该会向您显示错误。

After位于[Unit]部分,而不位于[Install]中。

一旦我解决了问题,您的脚本就对我有用。其他要检查的内容:

  • 日志文件路径是绝对路径吗?
  • 启动该服务的用户是否有权在此处进行写操作?

我建议只记录到stdout,再记录到日志,这样就不必担心轮换日志文件,占用多少空间等。journalctl对于查询日志也非常有用。您应该能够以非root用户身份(与脚本相同的用户)或位于组systemd-journal中来访问日记。


从那以后,我改用Loguru进行日志记录,这似乎更加直观和实用。

另外,将以下内容添加到.service文件中可确保日志记录不被缓冲并且是实时的:

1
2
[Service]
Environment=PYTHONUNBUFFERED=1

答案很简单,不会显示logging.info,但是会显示logging.warn(及更高版本)。