feat(config): add live slow-sql threshold setting

This commit is contained in:
2026-02-07 14:31:24 +08:00
parent 6a9858cdec
commit b84a5abb8a
28 changed files with 197 additions and 63 deletions

View File

@@ -21,6 +21,10 @@ _RECENT_LIMIT = max(10, int(os.environ.get("DB_SLOW_SQL_RECENT_LIMIT", "50") or
_MAX_EVENTS = max(_RECENT_LIMIT, int(os.environ.get("DB_SLOW_SQL_MAX_EVENTS", "20000") or 20000))
_SQL_MAX_LEN = max(80, int(os.environ.get("DB_SLOW_QUERY_SQL_MAX_LEN", "240") or 240))
_runtime_lock = threading.Lock()
_runtime_threshold_ms = _SLOW_SQL_THRESHOLD_MS
_runtime_sql_max_len = _SQL_MAX_LEN
_lock = threading.Lock()
_state = {
@@ -38,8 +42,29 @@ def _compact_text(value: str, max_len: int) -> str:
return f"{text[: max_len - 3]}..."
def _get_runtime_values() -> tuple[float, int]:
with _runtime_lock:
return float(_runtime_threshold_ms), int(_runtime_sql_max_len)
def configure_slow_sql_runtime(*, threshold_ms=None, sql_max_len=None) -> dict:
global _runtime_threshold_ms, _runtime_sql_max_len
with _runtime_lock:
if threshold_ms is not None:
_runtime_threshold_ms = max(0.0, float(threshold_ms))
if sql_max_len is not None:
_runtime_sql_max_len = max(80, int(sql_max_len))
return {
"threshold_ms": float(_runtime_threshold_ms),
"sql_max_len": int(_runtime_sql_max_len),
}
def _compact_sql(sql: str) -> str:
return _compact_text(str(sql or ""), _SQL_MAX_LEN)
_, sql_max_len = _get_runtime_values()
return _compact_text(str(sql or ""), sql_max_len)
def _compact_params(params_info: str) -> str:
@@ -165,12 +190,14 @@ def get_slow_sql_metrics_snapshot() -> dict:
total_events = len(events)
avg_duration_ms = round((total_duration_ms / total_events), 2) if total_events > 0 else 0.0
runtime_threshold_ms, _ = _get_runtime_values()
return {
"since_ts": int(float(events[0].get("time") or 0.0)) if events else 0,
"window_seconds": _WINDOW_SECONDS,
"top_limit": _TOP_LIMIT,
"recent_limit": _RECENT_LIMIT,
"slow_threshold_ms": _SLOW_SQL_THRESHOLD_MS,
"slow_threshold_ms": runtime_threshold_ms,
"total_slow_queries": total_events,
"unique_sql": len(grouped),
"avg_duration_ms": avg_duration_ms,