mirror of https://github.com/jumpserver/jumpserver
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
2.0 KiB
73 lines
2.0 KiB
6 years ago
|
# -*- coding: utf-8 -*-
|
||
|
#
|
||
|
import re
|
||
5 years ago
|
import os
|
||
5 years ago
|
import logging
|
||
6 years ago
|
from collections import defaultdict
|
||
|
from django.conf import settings
|
||
|
from django.core.signals import request_finished
|
||
|
from django.db import connection
|
||
|
|
||
5 years ago
|
from jumpserver.utils import get_current_request
|
||
6 years ago
|
|
||
6 years ago
|
from .local import thread_local
|
||
6 years ago
|
|
||
|
pattern = re.compile(r'FROM `(\w+)`')
|
||
5 years ago
|
logger = logging.getLogger("jumpserver.common")
|
||
5 years ago
|
DEBUG_DB = os.environ.get('DEBUG_DB', '0') == '1'
|
||
6 years ago
|
|
||
|
|
||
|
class Counter:
|
||
|
def __init__(self):
|
||
|
self.counter = 0
|
||
|
self.time = 0
|
||
|
|
||
|
def __gt__(self, other):
|
||
|
return self.counter > other.counter
|
||
|
|
||
|
def __lt__(self, other):
|
||
|
return self.counter < other.counter
|
||
|
|
||
|
def __eq__(self, other):
|
||
|
return self.counter == other.counter
|
||
|
|
||
|
|
||
|
def on_request_finished_logging_db_query(sender, **kwargs):
|
||
|
queries = connection.queries
|
||
|
counters = defaultdict(Counter)
|
||
|
for query in queries:
|
||
5 years ago
|
if not query['sql'] or not query['sql'].startswith('SELECT'):
|
||
6 years ago
|
continue
|
||
|
tables = pattern.findall(query['sql'])
|
||
|
table_name = ''.join(tables)
|
||
|
time = query['time']
|
||
|
counters[table_name].counter += 1
|
||
|
counters[table_name].time += float(time)
|
||
|
counters['total'].counter += 1
|
||
|
counters['total'].time += float(time)
|
||
|
|
||
|
counters = sorted(counters.items(), key=lambda x: x[1])
|
||
5 years ago
|
if not counters:
|
||
|
return
|
||
|
method = 'GET'
|
||
|
path = '/Unknown'
|
||
|
current_request = get_current_request()
|
||
|
if current_request:
|
||
|
method = current_request.method
|
||
|
path = current_request.get_full_path()
|
||
|
logger.debug(">>> [{}] {}".format(method, path))
|
||
6 years ago
|
for name, counter in counters:
|
||
|
logger.debug("Query {:3} times using {:.2f}s {}".format(
|
||
|
counter.counter, counter.time, name)
|
||
|
)
|
||
|
|
||
|
|
||
6 years ago
|
def on_request_finished_release_local(sender, **kwargs):
|
||
|
thread_local.__release_local__()
|
||
|
|
||
|
|
||
5 years ago
|
if settings.DEBUG and DEBUG_DB:
|
||
6 years ago
|
request_finished.connect(on_request_finished_logging_db_query)
|
||
5 years ago
|
else:
|
||
|
request_finished.connect(on_request_finished_release_local)
|