Skip to content

Database Query Logging — Logging and Monitoring Database Queries

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Database Query Logging. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Database query logging provides visibility into query performance, slow queries, Connection Pool usage, and database interaction patterns.

// TypeORM query logger
class PerformanceQueryLogger {
  constructor(options = {}) {
    this.slowQueryThreshold = options.slowQueryThreshold || 1000;
    this.maxQueryLength = options.maxQueryLength || 1000;
  }

  logQuery(query, parameters, duration) {
    const entry = {
      type: 'db_query',
      query: this.truncateQuery(query),
      parameters: this.sanitizeParameters(parameters),
      duration,
      timestamp: new Date().toISOString(),
      slow: duration > this.slowQueryThreshold
    };

    if (duration > this.slowQueryThreshold) {
      logger.warn(entry, 'Slow database query detected');
      metrics.timing('db.query.slow', duration, { query: query.split(' ')[0] });
    } else {
      logger.debug(entry);
    }

    metrics.timing('db.query', duration);
    metrics.increment('db.query.count', { operation: query.split(' ')[0].toLowerCase() });
  }

  truncateQuery(query) {
    return query.length > this.maxQueryLength
      ? query.slice(0, this.maxQueryLength) + '...'
      : query;
  }

  sanitizeParameters(params) {
    return params?.map(p => {
      if (typeof p === 'string' && p.length > 50) return '**TRUNCATED**';
      if (Buffer.isBuffer(p)) return '**BINARY**';
      return p;
    });
  }
}

// Sequelize logging configuration
const sequelize = new Sequelize({
  logging: (sql, timing) => {
    dbLogger.logQuery(sql, null, timing);
  },
  benchmark: true,
  logQueryParameters: true
});

Database query logging helps identify N+1 queries, missing indexes, and connection pool bottlenecks.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro