ElastAlertでアラート検出したtimestampのJST変換

はじめに

ElastAlertでアラート検出したインデックスのtimestampをUTCからJSTに変換する方法をご紹介します。

Version

ElastAlert 0.2.4

ElastAlertのルールにEnhancementsを実装

ElastAlertのルールのEnhancementsを実装すると、アラートを送信前にインデックスを変更することができます。
ElastAlert公式ドキュメントのEnhancements

UTC→JST変換処理

では、早速ですが、UTC→JST変換処理は、以下の通りです。

from datetime import timedelta, timezone
from elastalert.enhancements import BaseEnhancement
from elastalert.util import pretty_ts, ts_to_dt

class TimestameUtcToJstEnhancement(BaseEnhancement):

    def process(self, match):

        if '@timestamp' in match:
            # Generate JST timezone
            JST = timezone(timedelta(hours=+9), 'JST')
            # Convert type to datetime
            timestamp = ts_to_dt(match['@timestamp'])
            # Set new key 'timestamp_jst' and convert type to string.
            match['timestamp_jst'] = pretty_ts(timestamp.astimezone(JST), False)

コードの説明

ライブラリのインポート

以下のモジュールをインポートします。

  • JSTのタイムゾーンに必要なモジュールのインポート
    from datetime import timedelta, timezone
  • 次に、ElastAlertでEnhancementsを行うために継承するクラスのインポート
    from elastalert.enhancements import BaseEnhancement
  • そして、ElastAlert標準のtimestampを扱うライブラリのインポート
    from elastalert.util import pretty_ts, ts_to_dt

UTC→JST変換処理

BaseEnhancementを継承したクラスのprocess処理にて、@timestampのキーワードとマッチした場合、に次の処理を行います。

  1. JSTのタイムゾーンの設定
  2. timestamp形式の値をdatetime形式に変換します。
  3. timestamp_jstという新しいキーに、上記2にJSTタイムゾーンを設定し、UTCからJSTに変換し、pretty_ts()メソッドにて、datetime形式timestamp形式に戻した値を設定します。

    class TimestameUtcToJstEnhancement(BaseEnhancement):
    def process(self, match):
    
        if '@timestamp' in match:
            # Generate JST timezone
            JST = timezone(timedelta(hours=+9), 'JST')
            # Convert type to datetime
            timestamp = ts_to_dt(match['@timestamp'])
            # Set new key 'timestamp_jst' and convert type to string.
            match['timestamp_jst'] = pretty_ts(timestamp.astimezone(JST), False)

    ルールファイルのmatch_enhancements:に設定

    あとは、ルールファイルのmatch_enhancements:オプションに設定すれは、OKです。
    設定の詳細はElastAlert公式ドキュメント参照

まとめ

ElastAlertのアラートを送信直前にUTCからJSTにtimestampを変換する処理をご紹介でした。

タイトルとURLをコピーしました