---
title: Logging
description: "Log the SQL your Worker sends with an onQuery listener."
seo:
  description: "Log the SQL your Cloudflare Worker sends with an Active Record onQuery listener: every query app-wide, one request’s queries, Workers Logs, and Server-Timing."
---

## At a glance

| To                                     | Write                                                                    |
| -------------------------------------- | ------------------------------------------------------------------------ |
| log every query, app-wide              | `static override onQuery` on `ApplicationRecord`                         |
| log one request’s queries, with its ID | `withDatabase(connect(env.DB, { onQuery }), …)`                          |
| send the database time to the browser  | add up `durationMs` into a `Server-Timing` header                        |
| keep more attributes out of the logs   | `static override filterAttributes = [...Model.filterAttributes, "iban"]` |

## The Models

The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates, and the app’s Worker:

```ts user.ts
import { ApplicationRecord } from "./application-record";

export class User extends ApplicationRecord {}
```

```ts application-record.ts
import { Model, type QueryListener } from "@forestfuture/active-record";
import { schema } from "../db/schema";

export abstract class ApplicationRecord extends Model {
  static override schema = schema;

  // Every query, from every Model, whichever database runs it.
  static override onQuery: QueryListener = ({ model, sql, durationMs, error }) => {
    console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`, error ?? "");
  };

  // The defaults, plus an IBAN and a date of birth.
  static override filterAttributes = [...Model.filterAttributes, "iban", /^dateOfBirth$/];
}
```

```ts app.ts
import { User } from "./models/user";

// The app's Worker: here, one route that finds a user by email.
export const app = {
  async fetch(request) {
    const email = new URL(request.url).searchParams.get("email") ?? "";
    const user = await User.findByOrThrow({ email });
    return Response.json({ id: user.id });
  },
} satisfies ExportedHandler<Env>;
```

```ts schema.ts
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: cf0bc7e86bda

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** users — last changed by 0001_create_tables.sql */
export const users = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
  iban: "string",
  dateOfBirth: "string",
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    users: { attributes: users, primaryKey: "id" },
  },
  models: { User: "users" },
});

declare module "../models/user" {
  interface User extends TableAttributes<typeof users, (typeof User)["attributes"]> {}
}
```

```sql D1
CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL,
  iban TEXT,
  date_of_birth TEXT
);
```

```sql Postgres
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL,
  iban TEXT,
  date_of_birth TEXT
);
```

## Receiving each query

An `onQuery` listener is called once for every statement, writes and batches included, with:

| Field           |                                                                     |
| --------------- | ------------------------------------------------------------------- |
| `model`         | The Model’s class name, such as `"Product"`                         |
| `sql`, `params` | The statement and its bound values                                  |
| `durationMs`    | How long it took; in a D1 batch, D1’s own timing for each statement |
| `meta`          | The database’s result metadata, such as D1’s rows read and written  |
| `error`         | The database’s error, when it failed                                |

Send these wherever you like. A listener never changes a query’s outcome: one that throws is logged with `console.error`, and the query’s result stands.

Set a listener in one of two places:

|                           | Where                                                 | Knows the request? |
| ------------------------- | ----------------------------------------------------- | ------------------ |
| **Every query, app-wide** | `static override onQuery` on your app’s base class    | No                 |
| **One request’s queries** | `connect(env.DB, { onQuery })`, run in `withDatabase` | Yes                |

If both are set, the request’s listener runs first, then the base class’s.

## Logging every query

Set `onQuery` on your app’s base class, in `application-record.ts`, to see every statement of every Model:

```ts
import { Model, type QueryListener } from "@forestfuture/active-record";
import { schema } from "../db/schema";

export abstract class ApplicationRecord extends Model {
  static override schema = schema;

  // Every query, from every Model, whichever database runs it.
  static override onQuery: QueryListener = ({ model, sql, durationMs, error }) => {
    console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`, error ?? "");
  };

  // The defaults, plus an IBAN and a date of birth.
  static override filterAttributes = [...Model.filterAttributes, "iban", /^dateOfBirth$/];
}
```

It can’t tell requests apart. A Model can set its own `static override onQuery`, which replaces the base class’s for that Model.

## Logging one request’s queries

To group a request’s queries, open its database with a listener that knows the request, and run the request inside `withDatabase`:

```ts
import { withDatabase } from "@forestfuture/active-record";
import { connect } from "@forestfuture/active-record/d1";
import { app } from "./app";

// src/worker.ts: one request's queries, tagged with its ID, as JSON lines for Workers Logs.
export const worker = {
  fetch(request, env) {
    const requestId = request.headers.get("cf-ray") ?? crypto.randomUUID();
    const db = connect(env.DB, {
      onQuery: ({ model, sql, params, durationMs, error }) =>
        console.log(
          JSON.stringify({
            requestId,
            model,
            ms: Math.round(durationMs),
            sql,
            params, // a filtered attribute's value is "[FILTERED]"
            error: error instanceof Error ? error.message : undefined,
          }),
        ),
    });

    // Every query from a Model inside (User.findBy, user.save(), …) goes through db.
    return withDatabase(db, () => app.fetch(request));
  },
} satisfies ExportedHandler<Env>;
```

Logged as JSON, each line can be filtered by `requestId` in [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/). Turn them on with `"observability": { "enabled": true }` in your Wrangler config.

:::note
`withDatabase` needs Node.js compatibility, which is on by default for compatibility dates from 2026-08-04. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]`.
:::

## Logging only in development

Check a variable that only `.dev.vars` sets, such as `LOG_SQL=1`. For one request’s listener:

```ts
import { type QueryListener, withDatabase } from "@forestfuture/active-record";
import { connect } from "@forestfuture/active-record/d1";
import { app } from "./app";

// src/worker.ts, with LOG_SQL=1 in .dev.vars: logging in development only, nothing in production.
export const development = {
  fetch(request, env) {
    const onQuery: QueryListener | undefined = env.LOG_SQL
      ? ({ model, sql, durationMs }) => console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`)
      : undefined;

    return withDatabase(connect(env.DB, { onQuery }), () => app.fetch(request));
  },
} satisfies ExportedHandler<Env>;
```

The app-wide listener reads the variable from `cloudflare:workers` when a query runs:

```ts
import { Model, type QueryListener } from "@forestfuture/active-record";
import { env } from "cloudflare:workers";
import { schema } from "./db/schema";

// src/models/application-record.ts: logs only when LOG_SQL is set (in .dev.vars), read when a query runs.
export abstract class ApplicationRecord extends Model {
  static override schema = schema;

  static override onQuery: QueryListener = ({ model, sql, durationMs }) => {
    if ((env as { LOG_SQL?: string }).LOG_SQL) {
      console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`);
    }
  };
}
```

## Timing queries in the browser

To see a request’s database time in the browser’s developer tools, add it up, and send it as a `Server-Timing` header:

```ts
import { withDatabase } from "@forestfuture/active-record";
import { connect } from "@forestfuture/active-record/d1";
import { app } from "./app";

// src/worker.ts: the request's database time, under its Timing in the browser's developer tools.
export const timed = {
  async fetch(request, env) {
    let queries = 0;
    let total = 0;
    const db = connect(env.DB, {
      onQuery({ durationMs }) {
        queries += 1;
        total += durationMs;
      },
    });

    const response = await withDatabase(db, () => app.fetch(request));
    response.headers.append(
      "server-timing",
      `db;dur=${total.toFixed(1)};desc="${queries} queries"`,
    );
    return response;
  },
} satisfies ExportedHandler<Env>;
```

## Keeping secrets out of the logs

Listeners see the values of passwords, tokens, keys, and emails as `"[FILTERED]"`, while the database still gets the real values. [Serialization](/serialization#filtering-attributes) lists the attributes filtered by default, and everywhere their values are hidden.

### Filtering more attributes

Name them on your app’s base class, spreading in the defaults, as `ApplicationRecord` does with `iban` and `dateOfBirth`.

A string matches any attribute whose snake_case name contains it, so `"iban"` also covers `ibanNumber`. A string can be in camelCase or snake_case: `"ibanNumber"` and `"iban_number"` both match `ibanNumber`. Use a RegExp to match one name exactly.

### Seeing a filtered attribute

To see one while debugging, leave it out of the list in development:

```ts
import { Model } from "@forestfuture/active-record";
import { schema } from "../db/schema";

export abstract class ApplicationRecord extends Model {
  static override schema = schema;
  static override filterAttributes = Model.filterAttributes.filter((entry) => entry !== "email");
}
```

### Filtering `sql` fragments

A bare value inside an `sql` fragment has no attribute, so it’s logged as given. Write a secret as `column("token").value(token)`, or compare it with a condition such as `where({ token })`, and it’s filtered. Otherwise, leave `params` out of what you log.

> **Compared with Rails**
>
> Rails filters by its app-wide `filter_parameters`, against parameter and column names. Active Record keeps the list on the Model (`static filterAttributes`, inherited from your base class), and matches each entry against the attribute’s snake_case name, so `"_key"` filters `apiKey`. A RegExp may match either form. It also hides filtered values in cast errors and in `RecordNotFound`, which Rails’ filter doesn’t cover.
