Skip to content

Add SQL slow query logging and automatic EXPLAIN ANALYZE for queries exceeding threshold #884

Description

@RUKAYAT-CODER

Overview

Slow queries are only visible through external monitoring (APM, database logs). The application does not log slow queries itself, making it difficult to correlate slow query occurrences with specific request traces in structured logs.

Specifications

Features:

  • Log queries exceeding DB_SLOW_QUERY_THRESHOLD_MS (default 500ms) with the query text, parameters, and duration.
  • For queries exceeding DB_EXPLAIN_THRESHOLD_MS (default 2000ms), automatically run and log EXPLAIN ANALYZE.

Tasks:

  • Create a TypeORM custom logger (SlowQueryLogger) implementing Logger.
  • Override logSlowQuery(query, params, time) to emit structured log lines.
  • For queries over the explain threshold, issue EXPLAIN ANALYZE asynchronously and append to the log.
  • Register the logger in database.config.ts.

Impacted Files:

  • src/config/database.config.ts
  • New src/database/logging/slow-query.logger.ts

Acceptance Criteria

  • Queries over 500ms appear in structured logs with query text and duration.
  • Queries over 2000ms include EXPLAIN ANALYZE output in the log.
  • Logger is disabled in test environments to avoid noise.

Metadata

Metadata

Assignees

Labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions