Skip to content

feat: Add logging - #1042

Merged
Vinzent03 merged 15 commits into
mainfrom
feat/logger
Oct 4, 2024
Merged

Vinzent03 merged 15 commits into
mainfrom
feat/logger

Conversation

@Vinzent03

@Vinzent03 Vinzent03 commented Sep 24, 2024 •

Copy link
Copy Markdown
Collaborator

What kind of change does this PR introduce?

feature

What is the current behavior?

When debugging the auth broadcasting or the realtime/stream fixed I had to manually add many print statements, which was annoying. The js sdk already has some logging.

What is the new behavior?

Add logging via the logging package from dart.dev. This primarily only tracks the logs. When debug is true in the supabase_flutter Supabase instance, records with level INFO or higher are printed.
The logger instances are laid in a hierarchy separated by dots, which allows all supabase loggers to be united in a supabase logger instance.

@Vinzent03

Copy link
Copy Markdown
Collaborator Author

@dshukertjr For now, I've only added logging to the gotrue package. What do you think of this? If you consent, I would add this to the rest of the packages.

@dshukertjr

Copy link
Copy Markdown
Member

This is awesome! I love it so much!

@Vinzent03

Copy link
Copy Markdown
Collaborator Author

I've noticed that we should be careful with what data we log, especially sensitive data. So I've come up with the idea that records with level FINEST contain sensitive data like session data, or which postgrest urls are called. So that those records shouldn't be sent to sentry or similar without making such things clear in privacy notes. Let me know what you think of this approach and the documentation in the README of the supabase_flutter package, so I can add that section to the other packages as well.

@Vinzent03
Vinzent03 marked this pull request as ready for review October 4, 2024 12:00

@dshukertjr dshukertjr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great!

@Vinzent03

Copy link
Copy Markdown
Collaborator Author

I see now that there is no documentation in the README of the rest of the packages. So I would leave it for now only in the supabase_flutter package and you? or I? add it to the supabase website documentation.

@Vinzent03
Vinzent03 merged commit d1ecabd into main Oct 4, 2024
@Vinzent03
Vinzent03 deleted the feat/logger branch October 4, 2024 22:55
spydon added a commit that referenced this pull request Aug 14, 2026
Tier 3 of #1572, last of four PRs. Stacked on #1646 (→ #1645 → #1644).

The tier 3 note said the fetch wrappers are shareable in pieces, not as
one wrapper, since each is bound to its own exception type. These are
the pieces, now in `supabase_common`:

| Helper | Replaces |
| --- | --- |
| `request.sendWith(httpClient)` | `httpClient != null ?
httpClient.send(request) : request.send()` in functions, storage (3
sites) and the Iceberg catalog |
| `headers.header(name)` | case-insensitive header lookups on a response
|
| `headers.mediaType` | functions' `(headers['Content-Type'] ??
headers['content-type'] ??
'text/plain').split(';')[0].trim().toLowerCase()` and the Iceberg
catalog's `contentType.contains('application/json')` |
| `headers.redacted` | nothing; new, see below |
| `tryDecodeJsonObject(body)` | the "decode the error body, fall back to
the raw body" dance in storage and postgrest |

`supabase_common` gains a dependency on `http` (`^1.6.0`, the constraint
every other package already uses).

There is deliberately no shared helper for the "set `Content-Type`
unless the caller already did" check that storage and functions each had
inline. `BaseRequest.headers` is already a case-insensitive map, so once
the headers are on the request that check is just
`request.headers.putIfAbsent('Content-Type', ...)`, which is what all
three call sites now do. The Iceberg catalog moves to it as well, which
drops an ordering subtlety there: it previously relied on `...?headers`
spreading after a literal `'Content-Type'` key, so a caller who spelled
the header with any other casing ended up with two entries rather than
an override.

## Two behaviour changes

Both follow from setting the content type on the request rather than on
a detached map, and both are in functions' `invoke`:

- A body given as a `String` now goes out as `text/plain; charset=utf-8`
instead of a bare `text/plain`. `Request.body` fills the charset in
itself, and the old header copy ran afterwards and overwrote it.
- An explicit charset in a caller-supplied `Content-Type` now drives the
body encoding, because the header is in place before `Request.body`
reads it. Previously the body was always encoded as UTF-8 regardless of
what the caller asked for.

Relatedly, a multipart request no longer gets a content type from the
switch on the body type. It generates its own boundary while being
finalized and sets the header itself, so that default never reached the
wire.

## Credentials in the request logs

Raised in review. The logs interpolated the headers as sent, so
`_log.finest` handed the caller's `apikey` and access token to whatever
the logger writes to. `headers.redacted` replaces the value of every
credential-bearing header with `<redacted>` and keeps the names, since
knowing which headers went out is the useful part when reading a log. It
is applied to the request logs and the `Initialize with headers:` logs
in functions and storage.

Those log lines date back to #1042, so this is a pre-existing leak
rather than one this PR introduces, but it is fixed here since the
shared helper it needs is what this PR is adding.

## Two bugs this surfaces

Each has a regression test that fails without the fix.

**Postgrest swallowed typed errors for `maybeSingle()`.** The decode and
the `maybeSingle` handling shared one `try`/`catch (_)`:

```dart
try {
  final errorJson = jsonDecode(response.body) as Map<String, dynamic>;
  error = PostgrestException.fromJson(...);
  if (_maybeSingle) {
    return _handleMaybeSingleError(response, error); // rethrows `error` for a real failure
  }
} catch (_) {
  error = PostgrestException(message: response.body, ...); // ...and catches it here
}
```

`_handleMaybeSingleError` returns null data for the "0 rows" case and
rethrows otherwise, but that rethrow landed in the `catch (_)` and was
replaced by a generic exception built from the raw body. So a
`maybeSingle()` request that failed for a real reason lost its
`errorCode`, `details` and `hint`. Splitting the decode from the
handling fixes it.

**A JSON error body with unexpected field types crashed.** Removing that
catch-all exposed the next layer of the same problem:
`PostgrestException.fromJson` cast `code` and `hint` to `String` and
required a `String` message, so `{"code": 502, "message": "Bad
gateway"}` — a shape gateways really do return — threw a `TypeError` out
of the builder. Both `fromJson` factories now read every field
defensively, so any JSON object yields an exception.
`StorageException.fromJson` had the same casts and the same exposure.

The matching storage bug, where a JSON error body that is not an object
escaped as a `TypeError`, is fixed in #1644; here its inline guard
collapses into `tryDecodeJsonObject`.

## Not converted

Postgrest's own send site keeps managing its `Client` explicitly. It has
to close a client it created even when the response body fails midway,
and `BaseRequest.send` only closes its internal client when the stream
completes normally.

supabase_auth and postgrest also keep setting `Content-Type`
unconditionally rather than defaulting it with `putIfAbsent`: both
always JSON-encode the body, so honouring a caller-provided content type
there would mislabel the request rather than respect it.

The `Initialize with headers:` log in postgrest, realtime_client and
supabase_auth still prints the caller's `apikey` and access token. Those
packages are outside this refactor, and realtime's `params` map, which
carries the `apikey` too, is a `Map<String, dynamic>`, so covering it
needs a different shape of helper than the one on `Map<String, String>`.

## Testing

New `http_test.dart` in `supabase_common` covers each helper, plus the
three regression tests described above. Functions gains a test that a
caller-supplied charset is what the body is actually encoded with, a
test that no log record carries a credential value while every header
name stays readable, and its existing `text/plain` assertion is
tightened from `contains` to the full header value.

`melos analyze` and `melos format` clean; `dcm analyze` passes (its only
two hits are `avoid-inferrable-type-arguments` in `timestamp_test.dart`,
which is unchanged from `main`). The `supabase_auth`, `postgrest`,
`storage_client`, `functions_client`, `realtime_client`, `supabase`,
`supabase_common`, `supabase_flutter`, `supabase_typegen` and
`yet_another_json_isolate` suites pass. Capability matrix symbol and
drift checks pass.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Improved handling of malformed, unexpected, or non-object API error
responses.
- Preserved error details, including status codes, messages, hints,
codes, and additional information.
- Improved request and response handling across Functions and Storage,
including content types, media types, text encoding, and custom HTTP
clients.
  - Redacted credentials from request logs.

- **Tests**
- Added coverage for malformed errors, multiple-row responses, custom
clients, encoding, and HTTP utilities.

- **Documentation**
  - Updated descriptions of shared HTTP functionality.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants