# Telemetry: logs and traces

An app logs with Go's `log/slog` and records trace spans with `telemetry.Start`. The framework
already records a span for every request, statement, file, mail and call, and ties each log line
to its trace. None of it may hold personal data.

## Logs

`app.Main` makes the default `slog` logger write JSON lines to standard output, with the
`trace_id` and `span_id` of the context on every line that has one. Log with the context:

```go
slog.InfoContext(ctx, "user added")
slog.InfoContext(ctx, "report sent", "rows", len(rows))
```

- The framework logs what goes wrong on its side: an error a hook returned that answers 500, a
  refused form token, a page call that failed or a panic. Outside `aicoded dev` it logs only the
  error's kinds and codes, never its text; see "No personal data" below. So return an error
  instead of logging it.
- `aicoded dev` keeps each app's last 5000 log lines and shows them on the Logs page of the dev UI
  and through the `logs` tool of `aicoded mcp`. A line that is not JSON counts as `INFO`.

## Spans

The framework records these spans:

| Span | Attributes | For |
|---|---|---|
| `HTTP GET`, `HTTP POST`, … | `http.path` | every request the app serves, including its live connection |
| `sql.query`, `sql.exec`, `sql.begin` | `db.operation` | every statement; see [the SQL database](sql-database.md) |
| `filestore.<operation>` | `store` | every file store operation; see [file stores](file-stores.md) |
| `mailer.send`, `mailer.list`, … | | every mail call; see [mail](mail.md) |
| `rpc.call` | `rpc.app`, `rpc.method` | every call to another app; see [calls between apps](calls-between-apps.md) |

A call to another app carries the trace, so the called app's spans join the caller's trace.

To time your own work, start a span with the context, and end it:

```go
ctx, span := telemetry.Start(ctx, "users.add")
span.SetAttr("photos", strconv.Itoa(len(photos)))
defer span.End()
```

- `telemetry.Start` begins a child of the context's current span, or a new trace, and returns the
  context that carries the new span: pass it on, so the work inside becomes children of it.
- `SetAttr(key, value)` records a string attribute, and `RecordError(err)` marks the span as
  failed: with the error's text under `aicoded dev` in environment `dev`, and with its kinds and
  codes anywhere else.
- `End` hands the span to the runner. Calls after `End` do nothing.

`addUser` in the people example, which `Deps.AddUser` calls, records the error that ends it:

```go
defer func() {
	if err != nil {
		span.RecordError(err)
	}
	span.End()
}()
```

`aicoded dev` keeps each app's last 10000 spans and shows them on the Traces page of the dev UI,
as a tree with their timing, attributes and errors, and through the `traces` and `trace` tools of
`aicoded mcp`.

## On the platform

On the platform, the runner sends each app's output lines and spans to the platform's store, which
keeps them 30 days, marked with the app's organisation, name, release and environment, `preview`
or `production`, whatever the app sets. A line that is JSON keeps its level, trace and span; any
other line counts as `INFO`. You read them with your sign-in, for an app you own:

- `aicoded logs --env production` prints the newest log lines, and `aicoded traces --env
  production` the newest spans, or with `--trace <id>` those of one trace; see
  [the tools](tools.md);
- the `logs`, `traces` and `trace` tools of `aicoded mcp` read the same with `env` set to
  `preview` or `production`; see [MCP](mcp.md).

One read covers at most 7 days and 1000 rows, and the platform writes it to its audit log: who read
which app, the range and the filters, never the rows. On the platform, secret values are not
hidden from the logs: never log one.

## What the platform records about each request

Hosted by us, the runner, which carries every request to the app and every call it makes to an
outside service, records each one itself; the app cannot write, edit or remove these records;
what it answers (the status) is recorded as it is. It needs no code for them. For each request it
records:

- the page or path it reached, as the `access` section of the permission list names it, such as
  `/rooms/{id}`, `assets` for the app's assets, or `other` for any other path and for a page that
  answered 404: never the path or query that was typed;
- whether it was a page opened in the browser, another request or a live connection, its method
  and status, and how long the app took to answer it; a live connection is counted when it opens
  and never timed; a request whose viewer left before the app answered has status 0 and is not
  counted as failed;
- for a call to an outside service, the `egress` entry it matched, or `other` for a call that
  matched none, its status or the code of its refusal, and how long it took;
- for a request of a viewer in production, a pseudonym of the viewer, described below; never in
  preview and never for a call to an outside service.

Calls a page makes in its live connection, such as page calls and live updates, are part of that
connection: a page whose work is done by calls shows no latency or failures of its own.

From these records the platform shows each app's health: requests per second, latency and
failures, by page and outside service. You read it with your sign-in, for an app you own, with
`aicoded health` or the `health` tool of `aicoded mcp`; see [the tools](tools.md). In the console,
the app's owner, the organisation's admins and security admins, and the platform's operator, whose
reads as operator are written to the audit log, see its health; the app's owner and the organisation's
admins and security admins also see its usage: how many people opened it and which pages, as
numbers only. The records are kept 32 days; health by the minute 14 days and by the hour 90 days;
the daily usage numbers 13 months. Usage and health are Hosted by us only for now: In your own cloud the runner
records none of this, and a read is refused with E-REL-011.

The viewer's pseudonym is the first 16 bytes of an HMAC-SHA256 of the viewer's sign-in, with a
key of 32 random bytes that the platform keeps for each app and never gives to the app. That is
not what E-LINT-008 forbids: a hash the app makes of the viewer's identity can be made again by
anyone who has the app's code and the identity, so it names the viewer wherever the hash goes. The
platform's key is outside the app, so neither the app nor a reader of its logs can make the
pseudonym, and one person's pseudonyms in two apps cannot be joined by anyone without the
platform's keys. The platform's operator holds those keys and could compute a known person's
pseudonym; the data processing description says so. With the key, the operator could read that
person's times and pages in one app; and with a small audience, the usage counts are close to
personal. It is still personal data: it is kept 32 days with the records and is never shown in
the console, the API or the tools; usage shows only counts.

## No personal data

Logs and spans reach more tools and more people than the app's data does. Never put personal
data in them: no form values, names, logins, email addresses, uploaded file names or message
texts, and no secret.

- Log that something happened and its outcome, never what a viewer wrote. Count instead of
  listing: the people example's span holds the number of photos, not their names.
- An error's text can quote a value, such as the duplicate entry a UNIQUE index refuses or the
  name of a stored file. So wherever the framework records an error, in its log lines and in
  `RecordError`, it keeps only the error's kinds and codes outside `aicoded dev`: E-codes, MySQL
  error numbers, status codes, the sentinels of `io/fs`, `database/sql` and `context`, the
  operation of a file error, and the Go type of any other error. An error of a file store reads
  like `fs.PathError write: fs.ErrNotExist`, a duplicate entry `MySQL error 1062 (23000)`, and an
  error from `errors.New` `*errors.errorString`. A panic's value is recorded by its Go type.
- Under `aicoded dev` in environment `dev`, whose data is made up, the framework records the
  whole text and the panic's value, so that you and your AI assistant see what went wrong.
- The error the app gets back still holds the text. Return it from the hook, page call or
  function, or pass it to `RecordError`, and the framework records it as above; never log it
  or put it in a span attribute.
- `aicoded check` refuses a log line, a print or a span that records a value from outside the
  app (E-LINT-008): a form value, a URL parameter, the request, the viewer's identity, a value
  from the database, a mail from the inbox, a stored file, a secret, the input of a page call, of
  a `Validate` hook or of a function the app serves to other apps, or another app's answer, and
  any text, error or struct made from one, a hash included. The code of a template's expressions
  is checked too. Numbers and booleans carry nothing, so ids, counts, lengths and flags may be
  logged.
- A request span records the path, so a value in a URL, such as a login in `/users/alice`, is in
  the span. Keep data that must not be traced out of URLs.

## See also

- [aicoded dev](dev.md): the Logs and Traces pages.
- [MCP](mcp.md): the `logs`, `traces`, `trace` and `health` tools.
- [The tools](tools.md): `aicoded logs`, `aicoded traces` and `aicoded health`.
- [people/deps/users.go](https://github.com/AiCoded-Dev/framework/blob/93c19e3c1d22bcb6819d69eeaf91e7dd992eeb21/examples/people/deps/users.go): a span of its own, with no personal
  data.
