
私は定期的に長時間 (~5 日間) のデータ処理プログラムを実行しています。Ubuntu を使用しており、 経由で systemd 一時タスクで コマンドを実行していますsystemd-run --unit data_import /path/to/my-script.sh
。うまく動作しています。 でスクリプトのログ標準出力を確認できますjournalctl -u data_import.service
。
スクリプトからの stdout (および stderr) を systemd ジャーナルだけでなくファイルにも保存したいと思います。systemd-run --unit data_import -p "StandardOutput=file:/path/my-logging-file.txt …
stdout がそのファイルに保存されることはわかりました。 ただし、journald にログは記録されません。 引数を 2 回指定しようとしましたsystemd-run -p "StandardOutput=file:/path/my-logging-file.txt" -p "StandardOutput=journal" …
が、うまくいきませんでした。
systemdでstdoutをファイルに記録することは可能ですか?そしてsystemd ジャーナルに? (stderr も同様?)
Ubuntu 18.04 & 20.04、systemd v250。またはv245など
答え1
できないと思いますが、参考文献が1つ見つかりましたhttps://www.freedesktop.org/software/systemd/man/systemd.exec.html#StandardOutput=役に立つかもしれない(注意していずれか1つを取る弦)。
実行されたプロセスのファイル記述子 1 (stdout) が接続される場所を制御します。いずれか1つを取るinherit、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
...
このようなシステムでは、数か月後に数百のログを回避するために logrotate を構成する必要があります。
答え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 を設定するか、StandardOutput 引数に「append」を追加します。その後、次の操作を実行します。
systemctl daemon-reload
systemctl start *The name of your service*
サービスの起動時に開始を有効にするには:
systemctl enable *The name of your service*
サービス ファイル内のログ引数のソース:ここ