Logging
It is possible to set up logs for all queries executed by Kysely
using the log
in the constructor.
There are 2 ways to configure it :
1. Pass an array with the log level
You can give an array of log levels to the log
property in the Kysely
constructor. The possible values are 'query'
and 'error'
.
const db = new Kysely({
dialect: new PostgresDialect(postgresConfig),
log: ['query', 'error']
2. Pass a function to the log property
Passing function to the Kysely
constructor. The function will be called with a log event for each query executed.
The LogEvent
interface looks like this :
interface LogEvent {
level: 'query' | 'error';
query: CompiledQuery;
queryDurationMillis: number;
error: unknown; // only present if level is 'error'
}
you can also use the function signature to have more flexibility on how you want to log the queries.
const db = new Kysely({
dialect: new PostgresDialect(postgresConfig),
log(event) {
// you may want to log only the errored query :
if (event.level === "error") {
console.error("Query failed : ", {
durationMs: event.queryDurationMillis,
error: event.error,
sql: event.query.sql,
params: event.query.parameters,
});
}
// or log all queries :
console.log("Query executed : ", {
durationMs: event.queryDurationMillis,
sql: event.query.sql,
params: event.query.parameters,
});
}
})
For more information check the docs for details on the interfaces KyselyConfig.