Last active
June 20, 2024 02:17
-
-
Save 6mini/89819ae9482d8fd6d74024839706aa2d to your computer and use it in GitHub Desktop.
파이썬(Python) 프로그램에서 에러가 발생했을 때 슬랙(Slack)으로 알림을 보내는 기능이다. send_slack_notification 함수를 통해 Slack API에 메시지를 전송하고, handle_error 함수를 통해 발생한 예외의 내용과 스택 트레이스를 슬랙으로 전송한다. 스택 트레이스가 길 경우, 여러 메시지로 분할하여 전송하며, 깔끔한 알림 시스템 구축을 위해 스레드의 댓글로 전송한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import requests | |
import traceback | |
import time | |
def send_slack_notification(blocks, thread_ts=None): | |
""" | |
Slack 채널에 메시지를 전송하는 함수이다. | |
Args: | |
blocks (list): Slack 메시지 블록의 리스트이다. | |
thread_ts (str, optional): 스레드의 타임스탬프이다. 지정된 경우 메시지를 해당 스레드에 전송한다. | |
Returns: | |
dict: Slack API 응답이다. | |
""" | |
SLACK_BOT_TOKEN = "your-slack-bot-token" | |
url = "https://slack.com/api/chat.postMessage" | |
headers = { | |
"Authorization": "Bearer " + SLACK_BOT_TOKEN, | |
"Content-Type": "application/json" | |
} | |
data = { | |
"channel": "your-slack-channel-id", | |
"blocks": json.dumps(blocks) | |
} | |
if thread_ts: | |
data["thread_ts"] = thread_ts | |
response = requests.post(url, headers=headers, data=json.dumps(data)) | |
if not response.ok: | |
print(f"메시지 전송 오류: {response.text}") | |
else: | |
return response.json() | |
def handle_error(e, program_name): | |
""" | |
발생한 예외를 처리하고 에러 메시지 및 스택 트레이스를 Slack으로 전송하는 함수이다. | |
Args: | |
e (Exception): 발생한 예외 객체이다. | |
program_name (str): 에러가 발생한 프로그램의 이름이다. | |
""" | |
exc_traceback = traceback.format_exc() | |
error_title = f"⚠️ ['{program_name}' 오류 발생] ⚠️" | |
error_msg = str(e) | |
# 에러 제목과 메시지를 포함하는 메인 메시지 블록 생성 | |
blocks = [ | |
{ | |
"type": "header", | |
"text": { | |
"type": "plain_text", | |
"text": error_title | |
} | |
}, | |
{ | |
"type": "section", | |
"text": { | |
"type": "mrkdwn", | |
"text": "에러 내용: " + error_msg | |
} | |
} | |
] | |
# 메인 에러 메시지를 Slack에 전송 | |
main_message_response = send_slack_notification(blocks) | |
thread_ts = main_message_response.get('ts') | |
# 에러 스택 트레이스를 Slack 스레드로 전송하며, 내용이 3000자를 초과하면 분할하여 전송 | |
max_chars = 3000 | |
if len(exc_traceback) > max_chars: | |
chunks = [exc_traceback[i:i+max_chars] for i in range(0, len(exc_traceback), max_chars)] | |
for chunk in chunks: | |
send_slack_notification([{"type": "section", "text": {"type": "mrkdwn", "text": chunk}}], thread_ts=thread_ts) | |
else: | |
send_slack_notification([{"type": "section", "text": {"type": "mrkdwn", "text": exc_traceback}}], thread_ts=thread_ts) | |
# 사용 예제 | |
def example_function(): | |
# 예를 들어, 0으로 나누기를 시도하여 에러를 발생시키는 코드 | |
result = 1 / 0 | |
return result | |
if __name__ == "__main__": | |
# 사용 예제 1 | |
try: | |
# 예제 함수 실행 | |
example_function() | |
except Exception as e: | |
# 에러가 발생하면 handle_error 함수를 호출하여 Slack으로 알림 전송 | |
handle_error(e, 'example_function') | |
# 사용 예제 2 | |
message = 'example_message' | |
send_slack_notification([{"type": "section", "text": {"type": "mrkdwn", "text": message}}]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment