Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions docs/plugins/wpgraphql-logging/how-to/log-rest-requests/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
---
title: "How To Guide: Log WordPress REST API Requests"
description: "Turn on logging of WordPress REST API requests in the WPGraphQL Logging plugin, exclude routes, and tell REST entries apart from GraphQL entries."
---

The WPGraphQL Logging plugin can log WordPress REST API requests alongside GraphQL requests. REST entries go through the same Monolog pipeline (processors, handlers and data sanitization) and show up on the same admin screen.

REST logging is off by default. Turning it on does not change how GraphQL requests are logged.

> \[!NOTE]
> The plugin still requires WPGraphQL to be active, even if you only want to log REST requests.

## Turn on REST logging

1. Go to **GraphQL Logs -> Settings** and open the **Basic Configuration** tab.
2. Make sure **Enabled** is checked.
3. Check **Log REST API Requests**.
4. Optionally, list routes to skip in **Exclude REST Routes**.
5. Save the settings.

These Basic Configuration settings also apply to REST requests:

| Setting | Effect on REST requests |
| ------------------- | --------------------------------------------------------------------------- |
| Enabled | Master switch. REST requests are not logged when it is off. |
| IP Restrictions | Only REST requests from these IPs are logged. |
| Data Sampling Rate | Only this percentage of REST requests is logged. |
| Log Response | Adds the response body to the entry. Error bodies are always logged. |
| Exclude Queries | Does not apply. Use **Exclude REST Routes** instead. |
| Log Points | Does not apply. Each REST request produces one entry. |

## What gets logged

The plugin writes one entry for each REST request served over HTTP, just before the response is sent. CORS preflight (`OPTIONS`) requests are skipped.

Requests that are not served over HTTP are not logged. That covers PHP calls to `rest_do_request()`, embedded (`_embed`) sub-requests and block editor preloads. A batch request (`/batch/v1`) is logged as one entry.

Each entry has:

* **Channel**: `wpgraphql_logging_rest`. GraphQL entries use `wpgraphql_logging`.
* **Message**: the method and route, for example `WP REST GET /wp/v2/posts`. The **Event** column on the All Logs screen shows this message.
* **Level**: `INFO`, or `ERROR` when the response status is 400 or higher.
* **Context**:
* `method`, `route` and `matched_route` (the registered route pattern, such as `/wp/v2/posts/(?P<id>[\d]+)`)
* `params`: the parameters the client sent (URL, query string, form body and JSON body). Endpoint defaults are left out.
* `status`: the HTTP status code
* `duration_ms`: time from dispatch until the response is ready to send, in milliseconds
* `errors`: the error body, when the status is 400 or higher
* `response`: the response body, when **Log Response** is on and the request succeeded

The usual `extra` data (memory usage, request headers, process ID and so on) is added by the default processors.

## Exclude routes

**Exclude REST Routes** takes a comma-separated list of routes. Each entry matches that route and every route below it, ignoring case and leading or trailing slashes.

```text
/wp/v2/users, /wp-site-health/v1
```

With this value, `/wp/v2/users` and `/wp/v2/users/me` are skipped, but `/wp/v2/users-extra` and `/wp/v2/posts` are still logged.

## Sanitize sensitive data

When **Data Sanitization** uses the **Recommended** rules, the plugin anonymizes `params.username`, `params.password`, `params.email` and `response.password` in REST entries.

For anything else, choose **Custom** rules on the **Data Management** tab and use dot notation against the context. For example, `params.token` or `params.billing.phone`.

## Tell REST and GraphQL entries apart

The channel column is stored in the database and can be filtered on. To show only REST entries on the All Logs screen, add a where clause:

```php
add_filter( 'wpgraphql_logging_logs_table_where_clauses', function ( array $where ) {
$where[] = [
'column' => 'channel',
'operator' => '=',
'value' => \WPGraphQL\Logging\Events\RestRequestLogger::CHANNEL,
];
return $where;
} );
```

The channel is also included when you download a log as CSV.

## Customize which REST requests are logged

REST requests use their own rule set, filtered with `wpgraphql_logging_rest_rules`. Rules receive the REST route in place of the GraphQL query string. See [How to add or remove a rule](../logger-add-remove-rules/index.md) for how to write a rule.

```php
add_filter( 'wpgraphql_logging_rest_rules', function ( array $rules ) {
$rules[] = new MyPlugin\Logging\Rules\OnlyCustomNamespaceRule();
return $rules;
} );
```

The `wpgraphql_logging_is_enabled` filter runs for both GraphQL and REST requests.

## Change or listen to REST entries

REST entries go through the event system under `Events::REST_REQUEST_SERVED`, so you can transform or subscribe to them like GraphQL events. See [How to use the pub/sub event system](../event-pub-sub/index.md).

```php
use WPGraphQL\Logging\Events\Events;
use WPGraphQL\Logging\Plugin;

Plugin::transform( Events::REST_REQUEST_SERVED, function ( array $payload ): array {
$payload['context']['site_region'] = 'eu-west';
return $payload;
} );
```
25 changes: 17 additions & 8 deletions docs/plugins/wpgraphql-logging/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ The plugin captures key events for the WPGraphQL event lifecycle (configurable)
* **Response Headers**
* **Request Results**

### WordPress REST API Requests (opt-in)

The plugin can also log WordPress REST API requests through the same pipeline, rules and admin screen. This is off by default. See [How to log WordPress REST API requests](how-to/log-rest-requests/index.md).

### Pub/Sub Event System

Built with developers and plugins in mind, the plugin allows users to listen to individual events and transform or collect data from those events.
Expand Down Expand Up @@ -50,12 +54,13 @@ By default the following settings are pre-configured.

### Basic Configuration

| Setting | Default Value | Description |
| --------------- | ---------------------- | ---------------------------------------------------- |
| Enabled | true | Master switch to enable/disable logging |
| Exclude Queries | `__schema,GetSeedNode` | To exclude introspection and Faust Seed Node queries |
| Data Sampling | 10% | Log only 10% of the queries |
| Log Points | Selects all | Which lifecycle events to log |
| Setting | Default Value | Description |
| --------------------- | ---------------------- | ---------------------------------------------------- |
| Enabled | true | Master switch to enable/disable logging |
| Exclude Queries | `__schema,GetSeedNode` | To exclude introspection and Faust Seed Node queries |
| Data Sampling | 10% | Log only 10% of the queries |
| Log Points | Selects all | Which lifecycle events to log |
| Log REST API Requests | false | Also log WordPress REST API requests |

### Data Management

Expand All @@ -75,7 +80,9 @@ By default the following settings are pre-configured.
* **Exclude Queries**: A comma-separated list of GraphQL query or mutation names to be excluded from logging.
* **Data Sampling Rate**: A dropdown to select the percentage of requests that will be logged.
* **Log Points**: A multi-select field to choose the specific WPGraphQL lifecycle events for which data should be logged.
* **Log Response**: A toggle to determine whether the GraphQL response body should be included in the log.
* **Log Response**: A toggle to determine whether the GraphQL response body should be included in the log. Also applies to REST API responses when REST logging is enabled.
* **Log REST API Requests**: Also log WordPress REST API requests. Off by default. See [How to log WordPress REST API requests](how-to/log-rest-requests/index.md).
* **Exclude REST Routes**: A comma-separated list of REST routes to skip, such as `/wp/v2/users`. Each entry also excludes the routes below it. Only used when REST logging is enabled.

### Data Management

Expand All @@ -85,14 +92,16 @@ By default the following settings are pre-configured.
* **Number of Days to Retain Logs**: Number of days logged should be stored.
* **Data Sanitization Enabled**: Enable data sanitization.
* **Data Sanitization Method**: Choose between two sanitization methods (default is recommended)
* **Recommended Rules (Default)**: The following fields will be removed from the event data.
* **Recommended Rules (Default)**: The following fields will be removed or anonymized in the event data.
* `request.app_context.viewer.data`
* `request.app_context.viewer.allcaps`
* `request.app_context.viewer.cap_key`
* `request.app_context.viewer.caps`
* `variables.username`
* `variables.password`
* `variables.email`
* `params.username`, `params.password`, `params.email` (REST API request parameters)
* `response.password` (for example, a newly created application password in a REST response)
* **Custom Rules**: Define your own sanitization rules by specifying fields to anonymize, remove, or truncate.

## Project Structure
Expand Down
1 change: 1 addition & 0 deletions llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ Documentation for the Headless WordPress Toolkit, a modern, framework-agnostic c
- [How To Guide: Update the Admin Grid](https://github.com/wpengine/hwptoolkit/blob/main/docs/plugins/wpgraphql-logging/how-to/admin-add-view-column/index.md): Learn how to add custom columns to the WPGraphQL Logging plugin admin logs table.
- [How To Guide: Add Data to an Event](https://github.com/wpengine/hwptoolkit/blob/main/docs/plugins/wpgraphql-logging/how-to/event-add-context/index.md): Learn how to add custom context data to WPGraphQL Logging event.
- [How To Guide: Use the Events Pub/Sub System](https://github.com/wpengine/hwptoolkit/blob/main/docs/plugins/wpgraphql-logging/how-to/event-pub-sub/index.md): Learn how to use the WPGraphQL Logging plugin's event pub/sub system to subscribe, transform, and emit events.
- [How To Guide: Log WordPress REST API Requests](https://github.com/wpengine/hwptoolkit/blob/main/docs/plugins/wpgraphql-logging/how-to/log-rest-requests/index.md): Turn on logging of WordPress REST API requests in the WPGraphQL Logging plugin, exclude routes, and tell REST entries apart from GraphQL entries.
- [How To Guide: Add a new Handler](https://github.com/wpengine/hwptoolkit/blob/main/docs/plugins/wpgraphql-logging/how-to/logger-add-handler/index.md): This guide shows how to log to a file using a Monolog handler, either in addition to the default WordPress database handler or as a replacement. It also covers per-instance overrides.
- [How To Guide: Add a new Processor](https://github.com/wpengine/hwptoolkit/blob/main/docs/plugins/wpgraphql-logging/how-to/logger-add-processor/index.md): Learn how to add custom Monolog processors to the WPGraphQL Logging plugin to transform log records.
- [How To Guide: Add or Remove a Rule](https://github.com/wpengine/hwptoolkit/blob/main/docs/plugins/wpgraphql-logging/how-to/logger-add-remove-rules/index.md): Learn how to create and register custom logging rules with the WPGraphQL Logging plugin.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,20 @@ class BasicConfigurationTab implements SettingsTabInterface {
*/
public const LOG_RESPONSE = 'log_response';

/**
* The field ID for whether to also log WordPress REST API requests.
*
* @var string
*/
public const LOG_REST_REQUESTS = 'log_rest_requests';

/**
* The field ID for the exclude REST routes text input.
*
* @var string
*/
public const EXCLUDE_REST_ROUTES = 'exclude_rest_routes';

/**
* Get the fields for this tab.
*
Expand Down Expand Up @@ -134,6 +148,23 @@ public function get_fields(): array {
__( 'Whether or not to log the response from the WPGraphQL query into the context object.', 'wpgraphql-logging' ),
);

$fields[ self::LOG_REST_REQUESTS ] = new CheckboxField(
self::LOG_REST_REQUESTS,
self::get_name(),
__( 'Log REST API Requests', 'wpgraphql-logging' ),
'',
__( 'Also log WordPress REST API requests. Uses the same Enabled, IP Restrictions, Data Sampling Rate and Log Response settings as GraphQL logging. Log Points and Exclude Queries do not apply.', 'wpgraphql-logging' ),
);

$fields[ self::EXCLUDE_REST_ROUTES ] = new TextInputField(
self::EXCLUDE_REST_ROUTES,
self::get_name(),
__( 'Exclude REST Routes', 'wpgraphql-logging' ),
'',
__( 'Comma-separated list of REST route prefixes to exclude from logging. Only used when Log REST API Requests is enabled.', 'wpgraphql-logging' ),
__( 'e.g., /wp/v2/users, /wp-site-health/v1', 'wpgraphql-logging' )
);

return apply_filters( 'wpgraphql_logging_basic_configuration_fields', $fields );
}

Expand Down
10 changes: 10 additions & 0 deletions plugins/wpgraphql-logging/src/Events/Events.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,14 @@ final class Events {
* @var string
*/
public const REQUEST_RESULTS = 'graphql_request_results';

/**
* WordPress filter: rest_pre_serve_request.
*
* A WordPress REST API request is about to be served. Only used when
* REST API request logging is enabled.
*
* @var string
*/
public const REST_REQUEST_SERVED = 'rest_pre_serve_request';
}
Loading
Loading