# Create an alert rule

Alert on a burst of events, many affected users, a release whose crash-free sessions drop, events that are refused or lost, or chosen new issues, with filters, mail and Slack, Teams, Discord or JSON webhooks.

Alert rules come on top of the default alerts (see [Set the default alerts](set-default-alerts.md)).
Replace _project-id_ with the project's id and _rule-id_ with the rule's id.

## Prerequisites

- Permission for `errors:PutAlertRule` on the project to create, change or test a rule, and
  `errors:DeleteAlertRule` to delete one. Without them, the console shows those actions as
  unavailable with the note "Needs errors:PutAlertRule on this project" (or
  "Needs errors:DeleteAlertRule on this project").
- In the console, also `errors:ListProjects` on the project to open it, and `errors:ListAlertRules`
  on it: without it, the **Settings** tab has no **Alert rules** section.

## Triggers

| When                                    | Fires when                                                                                                                                               | Checked              |
| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| A new issue, a regression or a comeback | one of the chosen kinds happens to an issue, as for the default alerts                                                                                   | as the event arrives |
| An issue gets many events               | an issue reaches the number of events within the window (1 to 1440 minutes)                                                                              | every minute         |
| An issue affects many users             | an issue reaches the number of distinct users within the window                                                                                          | every minute         |
| A release's crash-free sessions drop    | a release's crash-free sessions over the last hour fall below the percentage, with at least the minimum number of sessions in that hour (100 by default) | every minute         |
| Events are refused or lost              | what the project sent that was refused, lost after acceptance, or both, reaches the number (1 by default) within the window of 1 to 24 hours             | every minute         |

A rule fires at most once per issue (or, for crash-free sessions, per release; for refused or lost
events, per project) within its quiet period, 30 minutes by default and up to a week.

**Events are refused or lost** counts every kind of data the project sent (error events,
transactions, sessions, profiles and the others on the **Stats** tab; see
[Monitoring](monitoring.md)), but not what the SDK dropped itself. Counts are kept per clock hour:
a window of 1 hour is the current hour, and a window of 3 hours is the current hour and the two
before it. The alert says how many were lost and refused, with the reasons, such as "error refused:
over the monthly cap (120)", and links to the **Stats** tab; a JSON webhook gets them all as
`dropped` (`total`, `lost`, `refused`, `windowHours`, `reasons`) with the `type`
`ews.errors.alert.dropped`. Lost after acceptance should always be zero, so 1,
the default, is the useful number for it.

Filters narrow the issues a rule applies to; each filter you set must match: levels, environments,
words the title contains (any case), and, through the CLI or the API, tags of the issue's latest
event. An issue rule (new, regression, comeback) matches the environments of the events that
caused it, not every environment the issue was ever seen in: a staging event never fires a
production rule. An events or users rule counts only the events of its environments, and never
fires for an ignored issue. A crash-free rule uses only the environments, which you set through the CLI or the
API: the console shows no filters for it. A rule for refused or lost events uses no filters.

## Create the rule

**Console**
1. Open the project, then the **Settings** tab.
2. Under **Alert rules**, choose **New rule**.
3. For **Name**, enter a name.
4. For **When**, choose the trigger, then fill in its values: **Events, at least** or
   **Users, at least** with **Within (minutes)**, or **Crash-free sessions below (%)** with
   **With at least (sessions)**, or, for issues, turn on the kinds to alert on (a new issue, a
   regression, an ignored issue that comes back). For **Events are refused or lost**, enter
   **Events, at least** and **Within (hours)**, and turn
   **Refused: over a limit or cap, invalid, or our service busy** and
   **Lost after acceptance: our fault, should never happen** on or off (both start on).
5. (Optional, not for crash-free sessions or refused or lost events) For **Only levels**, **Only environments** and
   **Only titles containing**, enter values, separated by commas.
6. Choose who is told: turn **Mail the organization’s owners and admins** on or off, enter
   addresses for **Also mail**, or enter an `https://` URL for **Webhook** and choose its
   **Format**.
7. (Optional) For **Quiet period (minutes)**, enter how long the rule waits before firing again for
   the same issue or release.
8. Choose **Create rule**.

The console proposes a rule for 100 events within 10 minutes, mailed to the owners and admins.

**CLI**
```sh
dcloud errors alert-rules create project-id --name "Checkout errors" \
  --trigger '{"kind":"frequency","events":100,"windowMinutes":10}' \
  --filters '{"levels":["error","fatal"],"environments":["production"],"tags":[],"titleContains":"checkout"}' \
  --actions '{"kind":"webhook","url":"https://hooks.slack.com/services/T000/B000/XXXX"}'
```

**API**
```http
POST /errors/api/projects/project-id/alert-rules
{
  "name": "Checkout errors",
  "trigger": { "kind": "frequency", "events": 100, "windowMinutes": 10 },
  "filters": { "levels": ["error", "fatal"], "environments": ["production"], "tags": [], "titleContains": "checkout" },
  "actions": [
    { "kind": "email", "admins": true, "addresses": ["oncall@example.com"] },
    { "kind": "webhook", "url": "https://hooks.slack.com/services/T000/B000/XXXX" }
  ],
  "throttleMinutes": 30
}
```

The other triggers are `{ "kind": "issue", "events": ["new", "regression", "escalating"] }`,
`{ "kind": "users", "users": 50, "windowMinutes": 60 }`,
`{ "kind": "crash_free", "belowPercent": 99, "minSessions": 100 }` and
`{ "kind": "dropped", "events": 1, "windowHours": 1, "outcomes": ["refused", "lost"] }` (each of
its fields may be left out for these defaults; `events` 1 to 10 000 000, `windowHours` 1 to 24,
`outcomes` at least one). A rule has 1 to 10 actions.
The answer is `201` with the rule.

## Webhook formats

With the format **Chosen from the URL** (`auto`), a URL on `hooks.slack.com` gets Slack's format,
one on a `webhook.office.com` or `logic.azure.com` host gets a Microsoft Teams Adaptive Card, a
`discord.com` or `discordapp.com` URL under `/api/webhooks/` gets Discord's format, and any other
URL gets JSON. Choose **Slack**, **Microsoft Teams**, **Discord** or **JSON** to set it yourself.

## Test, turn off, change or delete a rule

**Console**
1. Open the project, then the **Settings** tab.
2. Under **Alert rules**, open the rule's action menu and choose **Send a test**. The result, such
   as "sent: emailed 2; slack webhook 200", appears below the table.
3. To pause a rule, turn its **On** switch off; it is kept without firing.
4. To change it, choose **Edit**, then **Save**. The form shows a rule's first mail action and
   first webhook; tag filters and further actions, which only the CLI and the API set, are kept
   as they are. Change those through the CLI or the API.
5. To delete it and its history, choose **Delete**, then **Delete**.

**CLI**
```sh
dcloud errors alert-rules test project-id rule-id
dcloud errors alert-rules update project-id rule-id --throttle-minutes 60
dcloud errors alert-rules delete project-id rule-id
```

**API**
```http
POST /errors/api/projects/project-id/alert-rules/rule-id/test
```

```http
PATCH /errors/api/projects/project-id/alert-rules/rule-id
{ "enabled": false }
```

A change keeps the fields you leave out; `trigger`, `filters` and `actions` are replaced whole.

A test sends sample data at once, whatever the rule's quiet period and whether it is on. A mail or
webhook that fails is reported in the result, not as an error.

## Result

**Recently fired**, on the **Settings** tab, lists the project's last 50 firings, tests included,
with what was sent.

## Related

- [Set the default alerts](set-default-alerts.md)
- [Track release health](track-release-health.md)
- `errors.alert-rules.create` · `dcloud errors alert-rules create`
