Knex.js Query Logger for Express

raw JSON →
0.1.0 verified Thu Apr 23 auth: no javascript abandoned

This package provides Express middleware designed to log queries executed by Knex.js. It intercepts Knex query events and outputs them, typically to the console, for debugging and monitoring purposes within an Express application. The package is at version 0.1.0 and has seen no updates since its initial release over eight years ago, indicating it is abandoned. Its release cadence was effectively a single release. Key differentiators, if any existed, are now moot due to its lack of maintenance, especially concerning compatibility with modern Knex.js, Express, and Node.js versions which have evolved significantly since its last update. Users should be aware of potential incompatibilities and security risks.

error TypeError: app.use() requires a middleware function but got a undefined
cause The 'knex-logger' package failed to load or was imported incorrectly, resulting in 'knexLogger' being undefined or not a function.
fix
Verify that 'knex-logger' is installed, and ensure it's imported using CommonJS: const knexLogger = require('knex-logger');. Also, check if Knex.js instance is correctly passed to knexLogger(knexInstance).
error Queries are not being logged to the console.
cause The Knex.js instance passed to knex-logger might not be the one actively used for database operations, or the middleware is not correctly applied to the Express app.
fix
Ensure that app.use(knexLogger(yourKnexInstance)) is called before any routes that perform database queries, and that yourKnexInstance is the exact Knex instance performing those queries.
error Error: Cannot find module 'knex'
cause A dependency required by 'knex-logger' or its usage (`knex`, `express`, or `debug`) is not installed in the project.
fix
Install the missing dependency using npm: npm install knex express debug. Note that 'debug' might be an internal dependency and 'knex' and 'express' are external usage dependencies.
breaking The `knex-logger` package is severely outdated (v0.1.0, last updated 8+ years ago) and is incompatible with modern versions of Knex.js, Express, and Node.js. It uses deprecated APIs and will likely not function as expected or at all with current ecosystem versions.
fix Migrate to a maintained logging solution for Knex.js, or implement custom query logging using Knex's built-in event listeners (`query`, `query-response`, `error`).
gotcha Using this package in a production environment poses significant security risks due to its abandoned status. It has not received security updates and may contain vulnerabilities that could be exploited.
fix Do not use this package in production. If logging is required, use actively maintained alternatives or Knex's native logging capabilities.
gotcha The package relies on CommonJS module syntax (`require`). Attempting to import it using ES module syntax (`import`) in an ESM-only project will result in module resolution errors unless a transpilation step is configured.
fix Ensure your project is configured for CommonJS or use a build step (e.g., Webpack, Rollup, Babel) to transpile the module. For modern projects, consider alternatives that provide native ESM support.
npm install knex-logger
yarn add knex-logger
pnpm add knex-logger

This quickstart demonstrates how to integrate `knex-logger` as Express middleware to automatically log all database queries made by a Knex.js instance.

// knexfile.js
const path = require('path');
module.exports = {
  development: {
    client: 'sqlite3',
    connection: {
      filename: path.resolve(__dirname, './dev.sqlite3')
    },
    useNullAsDefault: true,
  },
};

// app.js
const express = require('express');
const knex = require('knex');
const knexLogger = require('knex-logger'); // CommonJS import as per package status
const path = require('path');

const env = process.env.NODE_ENV || 'development';
const knexConfig = require('./knexfile.js')[env];
const db = knex(knexConfig); // Initialize Knex instance

const app = express();

// Apply the knex-logger middleware
app.use(knexLogger(db));

// Example route that uses Knex
app.get('/users', async (req, res) => {
  try {
    const users = await db('users').select('*');
    res.json(users);
  } catch (error) {
    console.error('Error fetching users:', error);
    res.status(500).send('Internal Server Error');
  }
});

// Basic setup to listen
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
  // Create a dummy table if it doesn't exist for demonstration
  db.schema.hasTable('users').then(exists => {
    if (!exists) {
      return db.schema.createTable('users', table => {
        table.increments('id').primary();
        table.string('name');
        table.string('email');
      })
      .then(() => db('users').insert([{ name: 'Alice', email: 'alice@example.com' }, { name: 'Bob', email: 'bob@example.com' }]));
    }
  });
});