Add a logi custom handler for serializing non-JSON stuff (fix sql parameter serialization)

This commit is contained in:
Alex Gleason 2025-01-28 19:37:45 -06:00
parent 49735ce1fe
commit 5f99bddb42
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7
2 changed files with 26 additions and 23 deletions

View file

@ -8,38 +8,25 @@ import { errorJson } from '@/utils/log.ts';
/** Log the SQL for queries. */ /** Log the SQL for queries. */
export const KyselyLogger: Logger = (event) => { export const KyselyLogger: Logger = (event) => {
const { query, queryDurationMillis } = event; const { query, queryDurationMillis } = event;
const { sql } = query; const { parameters, sql } = query;
const duration = queryDurationMillis / 1000; const duration = queryDurationMillis / 1000;
dbQueriesCounter.inc(); dbQueriesCounter.inc();
dbQueryDurationHistogram.observe(duration); dbQueryDurationHistogram.observe(duration);
const parameters = query.parameters.map(serializeParameter);
if (event.level === 'query') { if (event.level === 'query') {
logi({ level: 'debug', ns: 'ditto.sql', sql, parameters, duration }); logi({ level: 'debug', ns: 'ditto.sql', sql, parameters: parameters as JsonValue, duration });
} }
if (event.level === 'error') { if (event.level === 'error') {
logi({ level: 'error', ns: 'ditto.sql', sql, parameters, error: errorJson(event.error), duration }); logi({
level: 'error',
ns: 'ditto.sql',
sql,
parameters: parameters as JsonValue,
error: errorJson(event.error),
duration,
});
} }
}; };
/** Serialize parameter to JSON. */
function serializeParameter(parameter: unknown): JsonValue {
if (Array.isArray(parameter)) {
return parameter.map(serializeParameter);
}
if (
typeof parameter === 'string' || typeof parameter === 'number' || typeof parameter === 'boolean' ||
parameter === null
) {
return parameter;
}
try {
return JSON.stringify(parameter);
} catch {
return String(parameter);
}
}

View file

@ -1,10 +1,26 @@
// Starts up applications required to run before the HTTP server is on. // Starts up applications required to run before the HTTP server is on.
import { logi } from '@soapbox/logi';
import { encodeHex } from '@std/encoding/hex';
import { Conf } from '@/config.ts'; import { Conf } from '@/config.ts';
import { cron } from '@/cron.ts'; import { cron } from '@/cron.ts';
import { startFirehose } from '@/firehose.ts'; import { startFirehose } from '@/firehose.ts';
import { startNotify } from '@/notify.ts'; import { startNotify } from '@/notify.ts';
logi.handler = (log) => {
console.log(JSON.stringify(log, (_key, value) => {
if (typeof value === 'bigint') {
return value.toString();
}
if (value instanceof Uint8Array) {
return '\\x' + encodeHex(value);
}
return value;
}));
};
if (Conf.firehoseEnabled) { if (Conf.firehoseEnabled) {
startFirehose(); startFirehose();
} }