はじめに
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
のキーワードとマッチした場合、に次の処理を行います。
JST
のタイムゾーンの設定timestamp形式
の値をdatetime形式
に変換します。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
を変換する処理をご紹介でした。