본문 바로가기

Project/ElasticStack

ElastAlert2 Alert UTC 타임존 문제 해결

0. 들어가며

Elasticsearch는 기본적으로 UTC 타임존을 사용하여 데이터를 저장합니다. 이는 시스템 간 일관성을 유지하는 데 유리하지만, 사용자나 클라이언트가 있는 지역에 맞춰진 로컬 타임존으로 데이터를 보여줘야 하는 경우에는 불편할 수 있습니다. 특히 Kibana와 같은 시각화 프로그램은 타임존을 자동으로 변환하여 표시하지만,

ElastAlert2는 기본적으로 이 기능을 제공하지 않기 때문에 알람에 표시되는 시간이 UTC로 나타납니다.

키바나 Discover에 표시되는 timestamp와 실제 document에 보여지는 timestamp
alert발송시 UTC timestamp를 나타내고있다.

1. Enhancement Module

ElastAlert2에서는 알람 발송 전에 사용자의 환경 또는 니즈에 맞춰서 알람 match를 변경할 수 있는 enhancement 모듈을

지원합니다. 이를 통해 타임스탬프 데이터를 알람이 전송되기 전에 적절한 타임존(KST)으로 변환할 수 있습니다.

 

2. 디렉토리/파일 생성

먼저 ElastAlert2의 디렉터리에 아래와 같은 구조로 디렉터리를 생성합니다.

[root@test ~]# cd /elastalert
[root@test elastalert]# mkdir elasticalert_modules
[root@test elastalert]# cd elasticalert_modules/
[root@test elasticalert_modules]# touch __init__.py
[root@test elasticalert_modules]# touch time_enhancement.py
[root@logmonitor elasticalert_modules]# ll
합계 0
-rw-r--r-- 1 root root 0  9월 25 12:25 __init__.py
-rw-r--r-- 1 root root 0  9월 25 12:26 time_enhancement.py

 

 

3. time_enhancement.py 작성

이제 타임존을 변환하는 실제 코드를 작성합니다.앞서 미리 생성해 둔  time_enhancement.py 파일을 수정하여 , ElastAlert2의 elastalert_modules 디렉터리에 저장합니다.

[root@test elastalert]# vi elastalert_modules/time_enhancement.py


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

class TimeEnhancement(BaseEnhancement):

    def process(self, match):
        # 매치에 '@timestamp' 키가 있으면 실행
        if '@timestamp' in match:
            # +9시간(KST: Korean Standard Time) 오프셋을 가진 타임존 생성 ('KST'라는 이름 지정)
            KST = timezone(timedelta(hours=+9), 'KST')
            
            # '@timestamp' 값을 datetime 형식으로 변환
            timestamp = ts_to_dt(match['@timestamp'])
            
            # UTC 시간에서 KST 시간으로 변환한 후, 사람이 읽기 쉽게 포맷하여 'timestamp_kst'에 추가
            match['timestamp_kst'] = pretty_ts(timestamp.astimezone(KST), False)

 

이 코드는 다음과 같이 작동합니다:

  1. 타임스탬프 확인: match 데이터에 @timestamp 필드가 존재하는지 확인합니다. 이 필드가 없으면 타임존 변환이 실행되지 않습니다.
  2. KST 타임존 생성: timezone과 timedelta를 사용하여 UTC+9 시간대에 해당하는 한국 표준시(KST)를 정의합니다.
  3. 타임스탬프 변환: ts_to_dt 함수로 @timestamp 값을 datetime 객체로 변환합니다.
  4. UTC → KST 변환: datetime 객체의 astimezone() 메서드를 사용해 UTC 시간을 KST 시간으로 변환합니다.
  5. KST 시간 추가: 변환된 KST 시간을 사람이 읽기 좋은 형식으로 포맷한 후, timestamp_kst라는 이름으로 match에 추가합니다. 

4. Rule 설정

ElastAlert2의 규칙(rule) 파일에 enhancements 옵션과 선언한 timestamp_kst를 추가하여

위에서 작성한 TimeEnhancement 클래스를 호출하도록 설정하면, 알람이 전송될 때 자동으로 로컬 타임존으로

변환된 시간이 포함됩니다.

[root@test elastalert]# vi rules/file_integrity_rule.yaml
###########중략###############

match_enhancements:
- "elastalert_modules.time_enhancement.TimeEnhancement"
# "filepath.filename.modulename(classname)"으로 작성

#@timestamp,timestamp_kst 각각 출력
alert_text_args: ["timestamp_kst","@timestamp"]
alert_text_type: alert_text_only
alert_text : |
  time : {0}
  UTC : {1}
###중략####

5. 마무리

위와 같이 기본적으로 UTC로 저장되는 Elasticsearch 데이터를 Elastalert2의 enhancement 모듈을 통해 

로컬 타임존으로 변환하여 사용자에게 알맞은 시간대에 맞춰 알람을 전송할 수 있습니다.

 

6. 참고 URL

https://elastalert2.readthedocs.io/en/latest/recipes/adding_enhancements.html#enhancements