0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

はじめに

日ごろの運用に欠かせない、ログローテーションに関して記述します。
Linux で稼働することを前提に、以下の処理を含むログローテーションをシェルで記述します。

  1. ログファイル名の変更 (アーカイブ目的)
  2. ログファイルの圧縮
  3. ログファイルの削除

処理内容

処理の全容は以下の通りです。変数で指定するディレクトリやファイル名、圧縮や削除のタイミングなどは、環境に合わせて変更しましょう。

全体
#!/bin/bash

#変数
log_directory='/usr/local/python/log/'
file_pattern='python.log'
file_pattern_compress='python*.log'
file_pattern_delete='python*.log.gz'
proc_date=`date '+%Y%m%d'`
compress_after=7
delete_after=30

#ファイル数分ループ
for file in log_directory
do
#アーカイブ
find $log_directory -name $file_pattern | xargs -I {} mv {} ${log_directory}python$proc_date.log
#圧縮
find $log_directory -mtime $compress_after -name $file_pattern_compress | xargs gzip -f
#削除
find $log_directory -mtime $delete_after -name $file_pattern_delete | xargs rm -f
done

1. ログファイル名の変更 (アーカイブ目的)

変更
find $log_directory -name $file_pattern | xargs -I {} mv {} ${log_directory}python$proc_date.log

find でログディレクトリからファイル名のパターンに合ったファイルを検索し、 アーカイブ用のファイル名に変更しています。
xargs は、前の処理結果を後続の処理に引数として引き渡すコマンドです。そのため、パイプの前で検索したファイル名を、パイプの後ろに引き継いで、ファイル名を変更する流れです。{ } は引数の位置を指定します。
結果、python.logを検索して、python20240809.log のようなファイル名に変更します。

2. ログファイルの圧縮

圧縮
find $log_directory -mtime $compress_after -name $file_pattern_compress | xargs gzip -f

find の条件に -mtime を指定して、最終更新日から compress_after で指定した日数が経過したものを圧縮しています。
結果、python20240809.log が圧縮され、python20240809.log.gz となります。

3. ログファイルの削除

削除
find $log_directory -mtime $delete_after -name $file_pattern_delete | xargs rm -f

find の条件に -mtime を指定して、最終更新日から delete_after で指定した日数が経過したものを削除しています。

最後に

Yellowfin が参照するデータを Python で処理し、その処理結果をログに出力する場合など、何もしなければ当然ログが肥大化します。
それがディスク容量の圧迫につながり、システム障害の原因となる可能性も否めません。

良いデータ分析のためにも、ログローテーションをはじめ、良い運用を行いましょう!

参考情報

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?