> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Logging and observability

> How the GatoJS logger works, exporting logs and traces to an OpenTelemetry collector, tracing your own code with withSpan, the default security headers, and the /api/healthcheck endpoint.

GatoJS ships a small observability layer in the `@gatojs/observability` workspace package (`packages/observability`). It gives you a logger built on the OpenTelemetry (OTel) logs API, an OTLP/HTTP exporter for logs and traces, and a `withSpan` helper. The core also sets security headers on every response and exposes a database healthcheck.

## The logger

```ts src/shared/lib/logger.ts theme={null}
import { createLogger } from "@gatojs/observability";
import { project } from "@/shared/config/project";

export const logger = createLogger(project.slug);
```

`logger` has `debug`, `info`, `warn` and `error` methods that take a message and optional attributes:

```ts theme={null}
import { logger } from "@/shared/lib/logger";

logger.error("[INVOICES] Failed to send invoice", { invoiceId, err: error });
```

Every entry is emitted to the OTel logs API. It is **also** printed to the console only when the app is not in production **and** no OTLP endpoint is configured.

### Where entries go

| `NODE_ENV` | `OTEL_EXPORTER_OTLP_ENDPOINT` | Console | OTLP export |
| - | - | - | - |
| not `production` (`npm run dev`, `npm test`) | unset | Yes, for example `[INFO] [MAILER] ...` with attributes | No |
| not `production` | set | No | Yes |
| `production` (`npm start`, Docker image) | set | No | Yes |
| `production` | unset | No | No: **entries are discarded** |

Both conditions are read once, when the logger module is imported, so changing them requires a restart.

> [!WARNING]
>
> **Set `OTEL_EXPORTER_OTLP_ENDPOINT` in production.** Without it, no application log entry is recorded anywhere: not command errors from `handleCommandError`, not failed email sends. Your platform's log view only shows what Next.js and libraries print themselves. The one exception is the environment validation report at startup, which goes straight to `console.error`.

### Attributes and error types

On export, attributes go through `normalizeAttributes`:

* an `Error` becomes three attributes: `<key>.type`, `<key>.message` and `<key>.stacktrace`;
* a `Date` becomes an ISO string, an object becomes a JSON string;
* `null` and `undefined` are dropped.

`<key>.type` comes from the error's `name` when it's a non-empty string other than `"Error"`, otherwise from the constructor name. Production builds minify class names, so a custom error class only keeps a readable type if it assigns its name as a **string literal**:

```ts theme={null}
export class InvoiceLockedError extends Error {
  name = "InvoiceLockedError"; // survives minification
}
```

`this.name = this.constructor.name` or `new.target.name` would turn into a minified name such as `d`. `npm run lint` enforces this: a `no-restricted-syntax` rule flags those patterns and flags any class that extends `Error` directly without its own `name`. Test files, `e2e/` and `.d.ts` files are exempt.

A subclass of `DomainError` without its own `name` inherits `"DomainError"`. If you want to tell your errors apart in logs, give each subclass its own `name`.

### Log messages

Core messages are in English with an area prefix: `[MAILER]`, `[USERS]`, `[AUTH]`, `[ORG]`. Follow the same convention in your features. The exception is `handleCommandError`, which logs the command's default (Polish) error message without a prefix, at `warn` for `DomainError` and `error` for anything else.

| Message | Level | Source |
| - | - | - |
| `[MAILER] SMTP_URL and RESEND_API_KEY not set, email not sent` | `info` | `mailer.ts` |
| `[MAILER] Failed to send password reset email` (and welcome, invitation variants) | `error` | `mailer.ts` |
| `[USERS] Welcome set-password email not delivered` | `error` | `invite-user-command.ts` |
| `[USERS] Impersonation started`, `[USERS] Impersonation stopped` | `info` | `impersonation-commands.ts` |
| `[AUTH] Failed to resolve active organization` | `error` | `default-organization-query.ts` |
| `[ORG] Failed to accept invitation`, `[ORG] Failed to set active organization` | `error` | `accept-invitation/[id]/page.tsx` |
| `trackAudit failed` | `error` | `src/shared/lib/audit.ts` (only with the `audit-logs` module) |

### `LOG_LEVEL` does nothing

`LOG_LEVEL` is in the env schema and `.env.example` sets it to `info`, but nothing reads it. The logger doesn't filter by level: `debug` entries are printed and exported just like `error`. Filter by severity in your log backend instead.

## OpenTelemetry export

`register()` in `src/instrumentation.ts` runs once when the server starts, in the Node.js runtime only. After the [environment check](https://docs.gatojs.com/configuration/environment-variables.md#at-startup), it sets up export only when an endpoint is configured:

```ts src/instrumentation.ts theme={null}
const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
if (!endpoint) {
  return;
}
const normalizedEndpoint = endpoint.replace(/\/$/, "");

const resource = resourceFromAttributes({
  "service.name": process.env.OTEL_SERVICE_NAME?.trim() || project.slug,
  "service.version": process.env.GIT_COMMIT_SHA ?? "dev",
  "deployment.environment.name": process.env.NODE_ENV ?? "development",
});
// logs  -> POST <endpoint>/v1/logs
// traces -> POST <endpoint>/v1/traces
```

| Variable | Purpose |
| - | - |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | Base URL of an OTLP/HTTP collector, **without** `/v1/logs`. Must include `http://` or `https://`. |
| `OTEL_EXPORTER_OTLP_HEADERS` | Headers for the collector, such as an API key, as `key=value,key2=value2`. Read by the exporter library. `OTEL_EXPORTER_OTLP_LOGS_HEADERS` overrides it for logs. |
| `OTEL_SERVICE_NAME` | `service.name` resource attribute. Defaults to the project slug. |
| `GIT_COMMIT_SHA` | `service.version`. Defaults to `dev`; nothing in the kit sets it, so wire it from your CI or platform. |

Any collector that accepts OTLP over HTTP with JSON works: an OpenTelemetry Collector, Grafana Cloud, Honeycomb, Axiom and similar services.

How export behaves:

* Logs and spans are sent in batches. Log records go out every 5 seconds by default.
* The kit doesn't flush on shutdown. On `SIGTERM` (a redeploy or restart), Next.js exits immediately, so entries from the last few seconds may be lost.
* Traces use `NodeTracerProvider` with an `AsyncLocalStorage` context manager and W3C propagation, so nested spans get the right parent.
* There is **no automatic instrumentation**: Prisma queries and HTTP requests don't produce spans. A span exists only where your code opens one.
* **No metrics provider is registered.** `meter` from `createTelemetry` works, but measurements go nowhere.

## Tracing your code with `withSpan`

`createTelemetry(serviceName)` returns `tracer`, `meter` and `withSpan(name, attributes, fn)`:

```ts theme={null}
import { createTelemetry } from "@gatojs/observability";
import { project } from "@/shared/config/project";

const { withSpan } = createTelemetry(project.slug);

const invoice = await withSpan("invoice.send", { invoiceId }, () =>
  sendInvoice(invoiceId),
);
```

`withSpan` opens an active span, runs `fn` and returns its result as a `Promise`, even for a synchronous function. On success it sets status `OK`. If `fn` throws or rejects, it records the exception, sets status `ERROR` and rethrows the same value. The span always ends.

## Security headers

`next.config.ts` adds the headers from `src/shared/lib/security-headers.ts` to every response (`source: "/(.*)"`), including `/api/*` routes and proxy redirects.

| Header | Effect |
| - | - |
| `X-Content-Type-Options: nosniff` | The browser won't guess a content type against `Content-Type`. |
| `X-Frame-Options: DENY` | No site, including your own, can embed the app in a frame (clickjacking protection). |
| `Referrer-Policy: strict-origin-when-cross-origin` | Other origins only see your origin in `Referer`, so tokens in URLs such as `/reset-password?token=...` don't leak. |
| `Permissions-Policy: camera=(), microphone=(), geolocation=()` | The page can't access the camera, microphone or location. A feature that needs them must change this core file. |
| `Strict-Transport-Security: max-age=63072000; includeSubDomains` | For two years, browsers connect to the domain and its subdomains over HTTPS only. Ignored over plain HTTP, such as `http://localhost:3000`. |

> [!NOTE]
>
> There is no `Content-Security-Policy` header. If your app needs one, add it to `security-headers.ts` and test it against the pages and third-party scripts you use.

## Healthcheck

```ts src/app/api/healthcheck/route.ts theme={null}
export const dynamic = "force-dynamic";

export async function GET() {
  try {
    await prisma.$queryRaw`SELECT 1`;
    return Response.json({ status: "ok", db: "ok" });
  } catch {
    return Response.json({ status: "error", db: "error" }, { status: 503 });
  }
}
```

| Request | Response |
| - | - |
| `GET` or `HEAD`, database reachable | `200` with `{"status":"ok","db":"ok"}` |
| `GET` or `HEAD`, database unreachable | `503` with `{"status":"error","db":"error"}` |
| `OPTIONS` | `204` with `Allow: GET, HEAD, OPTIONS` |
| Other methods | `405` |

What it tells you, and what it doesn't:

* **Public.** The proxy skips `/api`, and the handler checks no session. The response contains no data.
* **Database only.** A `200` means the process passed the startup env check, is running and can reach the database. A server with invalid env never answers at all, because it exits on startup.
* **Doesn't detect** values that pass validation but don't work (a wrong Resend key, an `APP_URL` on another domain), an empty database without tables (`SELECT 1` still works), or a redirect loop caused by a bad `HOSTNAME`, since `/api` bypasses the proxy.
* **Database errors aren't logged.** The `catch` returns `503` silently; check the database's own logs.
* **Timing.** A closed port fails immediately; an unreachable host waits up to 10 seconds (`connectionTimeoutMillis` in `src/shared/lib/prisma.ts`).

Use it as your platform's deployment healthcheck (see [Railway](https://docs.gatojs.com/deployment/railway.md)) or as a target for an uptime monitor.

## Related

> [card] [Environment variables](https://docs.gatojs.com/configuration/environment-variables.md)
>
> Full reference, including the OTel variables.

> [card] [Docker](https://docs.gatojs.com/deployment/docker.md)
>
> The production image and its runtime settings.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.