systemd 標準輸出到檔案並_到日誌?

systemd 標準輸出到檔案並_到日誌?

我經常做一個長時間運行(約 5 天)的資料處理程序。我正在使用 Ubuntu 並透過 systemd 瞬態任務運行命令systemd-run --unit data_import /path/to/my-script.sh。運作良好。我可以使用 來查看腳本的日誌記錄標準輸出journalctl -u data_import.service

我希望將腳本中的標準輸出(和標準錯誤)儲存到檔案以及 systemd 日誌中。我看到這systemd-run --unit data_import -p "StandardOutput=file:/path/my-logging-file.txt …會將標準輸出保存到該文件中。但是它不會記錄到日誌中。我兩次嘗試提供論點systemd-run -p "StandardOutput=file:/path/my-logging-file.txt" -p "StandardOutput=journal" …,但沒有成功。

systemd 是否可以將標準輸出記錄到檔案中到 systemd 日誌? (對於 stderr 也是如此?)

Ubuntu 18.04 和 20.04,systemd v250。或 v245 等

答案1

我想我們只能找到一個參考資料https://www.freedesktop.org/software/systemd/man/systemd.exec.html#StandardOutput=這可能會有所幫助(注意取其中之一細繩)。

控制已執行進程的檔案描述子 1 (stdout) 連接到的位置。取其中之一繼承、null、tty、journal、kmsg、journal+console、kmsg+console、file:path、append:path、truncate:path、socket 或 fd:name。

儘管我們可以更改預設的標準輸出類型。

答案2

您是否嘗試直接在腳本中建立日誌檔案並在每次需要時添加資訊?我知道這很明顯,但我很好奇它是否有效。

例如,使用 bash,直接在腳本中:

# Declaration
LOG=/var/log/your_script_log.log
# Or with a date 
TODAY=$(date +%Y-%m-%d)
LOG=/var/log/your_script_log-$(TODAY).log
...
# Beginning of main script
echo -e $TODAY > $LOG
...
# Every time needed during the script
if [[ $state == *"stopped"* ]];then
    echo "A very important message." >> $LOG
...

對於這樣的系統,您將需要配置日誌輪轉以避免幾個月後出現數百個日誌。

答案3

@Amandasaurus 好的,我明白了。然後我建議您在“/etc/systemd/system/[腳本的名稱].service”下建立服務文件並添加最少的必要資訊:

[Unit]
Description=*The name of your script*

[Service]
ExecStart=/path/to/my-script.sh
ExecStop=/bin/kill $MAINPID
KillMode=process
Type=simple
StandardOutput=/path_to_log/service.log
StandardError=/path_to_log/service_error.log

[Install]
WantedBy=multi-user.target

然後配置 logrotate 或將「append」加入到 StandardOutput 參數。之後執行以下操作:

systemctl daemon-reload
systemctl start *The name of your service*

若要啟用服務啟動時啟動:

systemctl enable *The name of your service*

服務文件中日誌參數的來源:這裡

相關內容