【systemd】ログを再起動時に消さない & ログ容量を制限する

2020.11.30

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

カフェチームの山本です。

カフェの機器では、Systemdを利用して、OS起動時に自動でプログラムを実行しています。systemdはログを出力するため、後から分析するときなどに便利です。

しかし、デフォルトの設定では、ログは再起動時にクリアされてしまうため、再起動を伴うエラー処理が走ったときに、ログを参照できないという問題があります。そこで、ログを消さないように設定を調べました。

また、ログを消さないようにすると、ログの容量が大きくなるため、空き容量が少ないとログで埋まってしまい、新しい処理ができなくなってしまいました。この対処として、ログファイルが使用する容量(ファイルサイズ)を制限する設定を調べたので、合わせてまとめておきたいと思います。

設定スクリプト

結論から述べると、/etc/systemd/journald.confの設定を変更することで、実現できます。変更する設定項目は、以下の2つです。

  • SystemMaxUse:journalのログが使用するディスクスペースの上限値。
  • Storage:ログを格納する場所。"persistent"を指定すると、電源ON/OFFでリセットされないディレクトリ("/var/log/journal")に出力されます。
# set max-log-size to 200MB
sudo sed -i 's/#*SystemMaxUse=.*/SystemMaxUse=200M/g' /etc/systemd/journald.conf
# set log not to be deteled on reboot
sudo sed -i 's/#*Storage=.*/Storage=persistent/g' /etc/systemd/journald.conf

これをスクリプトとして作成し、sudo shで実行すると、/etc/systemd/journald.confが以下のように書き換わります(長いので、一部省略しています)。

  • 変更前
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.
#
# Entries in this file show the compile time defaults.
# You can change settings by editing this file.
# Defaults can be restored by simply deleting this file.
#
# See journald.conf(5) for details.

[Journal]
#Storage=auto
#Compress=yes
(...)
#RateLimitBurst=1000
#SystemMaxUse=
(...)
#LineMax=48K
  • 変更後
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.
#
# Entries in this file show the compile time defaults.
# You can change settings by editing this file.
# Defaults can be restored by simply deleting this file.
#
# See journald.conf(5) for details.

[Journal]
Storage=persistent
#Compress=yes
(...)
#RateLimitBurst=1000
SystemMaxUse=200MB
(...)
#LineMax=48K

これによって、正しく設定することができました。(おそらくですが、再起動が必要だと思うので、OSごと再起動すると良いと思います。)

まとめ

/etc/systemd/journald.confの設定を変更することで、systemdのログを再起動後にも参照でき、ログファイルのサイズも制限することができました。他に設定項目も利用できそうです。短いですが、参考になれば幸いです。

参考にさせていただいたページ・サイト

journald.conf