반응형
    
    
    
  django 에서 한 view 내에서 사용되는 쿼리의 성능 체크를 라이브에서 하고 싶을 때 간단하게 signal callback 을 이용하여 쿼리타임을 계산하고, 일정 threshold 값 이상인 경우 슬랙 노티를 보내는 기능을 구현한다.
import requests
from django.db import connection
@receiver(request_finished)
def monitor_db_connection(sender, **kwargs):
    def send_slack_message(query, timer):        
        slack_message = {
            'channel': '#{channel_name}',
            "text": '*Elapsed Time*\n{} sec\n*Query*\n```{}```'.format(timer, query),
            'username': u'슬로우 쿼리 알림',
            'mrkdwn': 'true'
        }
        hook_url = 'https://hooks.slack.com/services/{hook_key}'
        requests.post(url=hook_url, data=slack_message)
    
    for q in connection.queries:
        try:
            time = float(q.get('time'))
            if time > 0.07: # 0.07 초가 넘는 쿼리는 슬랙 알림 발송
                send_slack_message(q.get('sql'), q.get('time'))
        except: pass
반응형
    
    
    
  '개발 이야기 > Django' 카테고리의 다른 글
| [Django] Replica DB 사용 시 읽기전용/쓰기전용 Database 분리하기 (0) | 2022.09.06 | 
|---|---|
| uwsgi processes, threads 값을 조정하여 서버 성능 향상하기 (0) | 2021.01.13 | 
| Request with Signature, Nonce by Using API Key & Secret pair & Validate Request (0) | 2020.12.30 | 
| Django Custom User Model & Custom Authentication (0) | 2020.12.30 | 
| django-extensions, jupyter 를 활용하여 브라우저로 django code 접근하기 (0) | 2020.12.14 | 
 
										
									 
										
									
댓글