# Advanced Log Querying and Filtering

Query and filter logs with regular expressions

The [Logs Explorer](/dashboard/project/_/logs-explorer) exposes logs from each part of the Supabase stack as a separate table that can be queried and joined using SQL.

![Logs Explorer](/docs/img/guides/platform/logs/logs-explorer.png)

You can access the following logs from the **Sources** drop-down:

- `auth_logs`: GoTrue server logs, containing authentication/authorization activity.
- `edge_logs`: Edge network logs, containing request and response metadata retrieved from Cloudflare.
- `function_edge_logs`: Edge network logs for only edge functions, containing network requests and response metadata for each execution.
- `function_logs`: Function internal logs, containing any `console` logging from within the edge function.
- `postgres_logs`: Postgres database logs, containing statements executed by connected applications.
- `realtime_logs`: Realtime server logs, containing client connection information.
- `storage_logs`: Storage server logs, containing object upload and retrieval information.

The Logs Explorer uses BigQuery and supports all [available SQL functions and operators](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators).

## Timestamp display and behavior

BigQuery stores each log entry with a `timestamp` as a `TIMESTAMP` data type. Use the appropriate [timestamp function](https://cloud.google.com/bigquery/docs/reference/standard-sql/timestamp_functions#timestamp) to utilize the `timestamp` field in a query.

BigQuery renders raw top-level timestamp values as Unix microseconds. To render the timestamps in a human-readable format, use the `DATETIME()` function to convert the Unix timestamp display into an ISO-8601 timestamp.

```sql
-- timestamp column without datetime()
select timestamp from ....
--  1664270180000

-- timestamp column with datetime()
select datetime(timestamp) from ....
-- 2022-09-27T09:17:10.439Z
```

## Unnesting arrays

Each log event stores metadata as an array of objects with multiple levels, as you can see by selecting single log events in the Logs Explorer. To query arrays, use `unnest()` on each array field and add it to the query as a join. This allows you to reference the nested objects with an alias and select their individual fields.

For example, to query the edge logs without any joins:

```sql
select timestamp, metadata from edge_logs as t;
```

The Logs Explorer renders the resulting `metadata` key as an array of objects in the Logs Explorer. In the following diagram, each box represents a nested array of objects:

![Without Unnesting](/docs/img/unnesting-none.png)

Perform a `cross join unnest()` to work with the keys nested in the `metadata` key.

To query for a nested value, add a join for each array level:

```sql
select timestamp, request.method, header.cf_ipcountry
from
  edge_logs as t
  cross join unnest(t.metadata) as metadata
  cross join unnest(metadata.request) as request
  cross join unnest(request.headers) as header;
```

This surfaces the following columns available for selection:
![With Two Level Unnesting](/docs/img/unnesting-2.png)

This allows you to select the `method` and `cf_ipcountry` columns. In JS dot notation, the full paths for each selected column are:

- `metadata[].request[].method`
- `metadata[].request[].headers[].cf_ipcountry`

## LIMIT and result row limitations

The Logs Explorer has a maximum of 1000 rows per run. Use `LIMIT` to optimize your queries by reducing the number of rows returned further.

## Best practices

1. Include a filter over **timestamp**

Querying your entire log history might seem appealing. For **Enterprise** customers that have a large retention range, you run the risk of timeouts due to additional time required to scan the larger dataset.

2. Avoid selecting large nested objects. Select individual values instead.

When querying large objects, the columnar storage engine selects each column associated with each nested key, resulting in a large number of columns being selected. This inadvertently impacts the query speed and may result in timeouts or memory errors, especially for projects with a lot of logs.

Instead, select only the values required.

```sql
-- ❌ Avoid doing this
select
  datetime(timestamp),
  m as metadata -- <- metadata contains many nested keys
from
  edge_logs as t
  cross join unnest(t.metadata) as m;

-- ✅ Do this
select
  datetime(timestamp),
  r.method -- <- select only the required values
from
  edge_logs as t
  cross join unnest(t.metadata) as m
  cross join unnest(m.request) as r;
```

## Examples and templates

The Logs Explorer includes **Templates** (available in the Templates tab or the dropdown in the Query tab) to help you get started.

For example, you can enter the following query in the SQL Editor to retrieve each user's IP address:

```sql
select datetime(timestamp), h.x_real_ip
from
  edge_logs
  cross join unnest(metadata) as m
  cross join unnest(m.request) as r
  cross join unnest(r.headers) as h
where h.x_real_ip is not null and r.method = "GET";
```

## Understanding field references

You query log tables with a subset of BigQuery SQL syntax. They all have three columns: `event_message`, `timestamp`, and `metadata`.

| column          | description                 |
| --------------- | --------------------------- |
| `timestamp`     | time event was recorded     |
| `event_message` | the log's message           |
| `metadata`      | information about the event |

The `metadata` column is an array of JSON objects that stores important details about each recorded event. For example, in the Postgres table, the `metadata.parsed.error_severity` field indicates the error level of an event. To work with its values, you need to `unnest` them using a `cross join`.

This approach is commonly used with JSON and array columns, so it might look a bit unfamiliar if you're not used to working with these data types.

```sql
select
  event_message,
  parsed.error_severity,
  parsed.user_name
from
  postgres_logs
  -- extract first layer
  cross join unnest(postgres_logs.metadata) as metadata
  -- extract second layer
  cross join unnest(metadata.parsed) as parsed;
```

## Expanding results

Logs returned by queries may be difficult to read in table format. A row can be double-clicked to expand the results into more readable JSON:

![Expanding log results](/docs/img/guides/platform/expanded-log-results.png)

## Filtering with [regular expressions](https://en.wikipedia.org/wiki/Regular_expression)

The Logs use BigQuery-style regular expressions with the [regexp_contains function](https://cloud.google.com/bigquery/docs/reference/standard-sql/string_functions#regexp_contains). In its most basic form, it checks if a string is present in a specified column.

```sql
select
  cast(timestamp as datetime) as timestamp,
  event_message,
  metadata
from postgres_logs
where regexp_contains(event_message, 'is present');
```

There are multiple operators that you should consider using:

### Find messages that start with a phrase

`^` only looks for values at the start of a string

```sql
-- find only messages that start with connection
regexp_contains(event_message, '^connection')
```

### Find messages that end with a phrase:

`$` only looks for values at the end of the string

```sql
-- find only messages that ends with port=12345
regexp_contains(event_message, '$port=12345')
```

### Ignore case sensitivity:

`(?i)` ignores capitalization for all proceeding characters

```sql
-- find all event_messages with the word "connection"
regexp_contains(event_message, '(?i)COnnecTion')
```

### Wildcards:

`.` can represent any string of characters

```sql
-- find event_messages like "hello<anything>world"
regexp_contains(event_message, 'hello.world')
```

### Alphanumeric ranges:

`[1-9a-zA-Z]` finds any strings with only numbers and letters

```sql
-- find event_messages that contain a number between 1 and 5 (inclusive)
regexp_contains(event_message, '[1-5]')
```

### Repeated values:

`x*` zero or more x
`x+` one or more x
`x?` zero or one x
`x{4,}` four or more x
`x{3}` exactly 3 x

```sql
-- find event_messages that contains any sequence of 3 digits
regexp_contains(event_message, '[0-9]{3}')
```

### Escaping reserved characters:

`\.` interpreted as period `.` instead of as a wildcard

```sql
-- escapes .
regexp_contains(event_message, 'hello world\.')
```

### `or` statements:

`x|y` any string with `x` or `y` present

```sql
-- find event_messages that have the word 'started' followed by either the word "host" or "authenticated"
regexp_contains(event_message, 'started host|authenticated')
```

### `and`/`or`/`not` statements in SQL:

`and`, `or`, and `not` are all native terms in SQL and can be used in conjunction with regular expressions to filter results

```sql
select
  cast(timestamp as datetime) as timestamp,
  event_message,
  metadata
from postgres_logs
where
  (regexp_contains(event_message, 'connection') and regexp_contains(event_message, 'host'))
  or not regexp_contains(event_message, 'received');
```

### Filtering and unnesting example

Filter for Postgres:

```sql
select
  cast(postgres_logs.timestamp as datetime) as timestamp,
  parsed.error_severity,
  parsed.user_name,
  event_message
from
  postgres_logs
  cross join unnest(metadata) as metadata
  cross join unnest(metadata.parsed) as parsed
where regexp_contains(parsed.error_severity, 'ERROR|FATAL|PANIC')
order by timestamp desc
limit 100;
```

## Limitations

### Log tables cannot be joined together

Each product table operates independently without the ability to join with other log tables. This may change in the future.

### The `with` keyword and subqueries are not supported

The parser does not yet support `with` and subquery statements.

### The `ilike` and `similar to` keywords are not supported

Although you can use `like` and other comparison operators, `ilike` and `similar to` are incompatible with BigQuery's variant of SQL. Use `regexp_contains` as an alternative.

### The wildcard operator `*` to select columns is not supported

The log parser is not able to parse the `*` operator for column selection. Instead, you can access all fields from the `metadata` column:

```sql
select
  cast(postgres_logs.timestamp as datetime) as timestamp,
  event_message,
  metadata
from
  <log_table_name>
order by timestamp desc
limit 100;
```