Skip to content

Instantly share code, notes, and snippets.

@chaitanyagupta
Last active September 14, 2021 03:02
Show Gist options
  • Save chaitanyagupta/57ad3e59d03c26a96363fff538e67874 to your computer and use it in GitHub Desktop.
Save chaitanyagupta/57ad3e59d03c26a96363fff538e67874 to your computer and use it in GitHub Desktop.
Format SQL statements in Postgres logs
// pg-format-sql.js
//
// Format SQL statements in Postgres logs
// i.e. If a log line contains a SQL statement, it will be transformed from this:
//
// 2021-09-14 08:02:37.255 IST [20200] LOG: statement: SELECT MAX("my_notification"."id") AS "latest_id", COUNT(*) AS "count" FROM "my_notification" WHERE ("my_notification"."is_unread" AND "my_notification"."organization_id" = 1 AND "my_notification"."recipient_id" = 2)
//
// to this:
//
// 2021-09-14 08:02:37.255 IST [20200] LOG: statement:
// SELECT
// MAX("my_notification"."id") AS "latest_id",
// COUNT(*) AS "count"
// FROM
// "my_notification"
// WHERE
// (
// "my_notification"."is_unread"
// AND "my_notification"."organization_id" = 1
// AND "my_notification"."recipient_id" = 2
// )
//
// To use this, you will need node/npm.
//
// Make sure to run `npm install sql-formatter` before you run this script
//
// Usage:
//
// cat /path/to/postgres/log | node pg-format-sql.js
// tail -f /path/to/postgres/log | node pg-format-sql.js
const readline = require('readline');
const format = require('sql-formatter').format;
const rl = readline.createInterface({
input: process.stdin
});
rl.on('line', line => {
let matches = line.match(/(^.*(?:statement|STATEMENT): *)(.*)/);
if (matches && matches.length > 0) {
console.log(matches[1]);
if (matches[2]) {
let indent = ' '.repeat(4);
let formatted = format(matches[2]);
console.log(formatted.split('\n').map(line => indent + line).join('\n'))
}
} else {
console.log(line);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment