【问题标题】:Log Python Systemd output to log file将 Python Systemd 输出记录到日志文件
【发布时间】:2019-04-24 14:43:41
【问题描述】:

我将我的 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_service.py 文件中,我使用日志模块记录输出:

import logging

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

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

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

我怎样才能做到这一点?

【问题讨论】:

    标签: python logging systemd


    【解决方案1】:

    我已经切换到使用Loguru 进行日志记录,它看起来更加直观和实用。

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

    [Service]
    Environment=PYTHONUNBUFFERED=1
    
    

    【讨论】:

    • 我的日志配置很好,但我大部分时间都看不到日志。这个解决方案为我解决了。我只是在我的 python 脚本上使用 print 并且日志配置在使用这一行的服务上 [Service] StandardOutput=file:/etc/mailbot/logs/mailbot.log
    【解决方案2】:

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

    After 进入 [Unit] 部分,而不是 [Install]

    一旦我确定您的脚本对我有用。其他需要检查的事项:

    • 日志文件路径是绝对路径吗?
    • 启动服务的用户是否有写入权限?

    我建议只记录到标准输出,记录到日志,这样您就不必担心轮换日志文件,它需要多少空间等。此外,journalctl 非常适合查询日志。您应该能够以非 root 用户身份访问日志,可以是与脚本相同的用户,也可以是 systemd-journal 组中的用户。

    【讨论】:

      【解决方案3】:

      答案很简单,logging.info 不会出现,但logging.warn(及以上)会出现。

      【讨论】:

        猜你喜欢
        • 2017-04-13
        • 2022-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多