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

fre*_*all 5 python logging systemd

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

[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 Code Online (Sandbox Code Playgroud)

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

import logging

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

问题是当我运行我启动我的文件时,这些信息没有被记录到我的日志文件中 systemctl

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

我怎样才能做到这一点?

fre*_*all 7

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

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

[Service]
Environment=PYTHONUNBUFFERED=1

Run Code Online (Sandbox Code Playgroud)