X日より古いWebサーバーログファイルの行を削除しますか?

X日より古いWebサーバーログファイルの行を削除しますか?

デフォルトの「デフォルト」ログ形式を使用してUbuntuでNginxを実行しており、次の出力が生成されます。

95.108.181.102 - - [11/Feb/2018:11:43:10 +0000] "GET /blog/ HTTP/1.1" 200 4438 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)" "-"

私は回転しないデフォルトのログファイルを持っており、これをGoAccess(ログ解析/レポートソフトウェア)と一緒に使用します。約30日以上経過したログエントリを含むファイルの行を削除したいと思います。これは可能ですか? bashステートメントを使用する方が良いですか?

これを既存の毎日のcronjobに追加して30日のローリングレポートを生成する予定です。次のようなものを使用したいが、ログを正しく解析することはできません。sed -i '/<magical-invocation-goes-here> --date="-30 days"/d' example.log

ベストアンサー1

牛に似た一種の栄養awk解決策:

サンプルtest.log:

95.108.181.102 - - [11/Feb/2018:11:43:10 +0000] "GET /blog/ HTTP/1.1" 200 4438 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)" "-"
95.108.181.102 - - [11/Aug/2017:11:43:10 +0000] "GET /blog/ HTTP/1.1" 200 4438 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)" "-"
95.108.181.102 - - [01/Jan/2018:11:43:10 +0000] "GET /blog/ HTTP/1.1" 200 4438 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)" "-"
95.108.181.102 - - [11/Feb/2018:11:43:10 +0000] "GET /blog/ HTTP/1.1" 200 4438 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)" "-"

awk -v m1_ago=$(date -d"-1 month" +%s) \
'BEGIN{ 
     split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", month);
     for (i in month) m_nums[month[i]] = i
 }
 { split(substr($4,2), a, "[/:]") }
 mktime(sprintf("%d %d %d %d %d %d", a[3], m_nums[a[2]], a[1], a[4], a[5], a[6])) > m1_ago
' test.log > tmp_log && mv tmp_log test.log

最終test.logコンテンツ:

95.108.181.102 - - [11/Feb/2018:11:43:10 +0000] "GET /blog/ HTTP/1.1" 200 4438 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)" "-"
95.108.181.102 - - [11/Feb/2018:11:43:10 +0000] "GET /blog/ HTTP/1.1" 200 4438 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)" "-"

おすすめ記事