# Log a zone's queries

Turn on query logging for a hosted zone, and read the queries the nameservers answered for it.

Replace _zone-id_ with the id of your hosted zone. With query logging on, every query the
nameservers answer for the zone becomes one line in its log, about a minute later, kept seven days:

```
www.example.com A NOERROR answers=1 udp 203.0.113.0/24 DO
```

The fields are the name, the type, the response code, the number of answers, the transport, the
client's network (a /24, or a /56 for IPv6, never its address), and `DO` or `ECS` when the query
asked for signatures or carried a client subnet. Each nameserver logs at most 1,250 lines a minute
for a zone, fewer when other zones that log their queries share that limit with it; queries past
it are counted in the metric (see [Monitoring](monitoring.md)) but not logged.

## Prerequisites

- Permission for `dns:UpdateQueryLogging` on the zone to turn logging on or off, and
  `dns:GetQueryLog` to read the log. In the console, without them, the tab says "Changing query
  logging needs dns:UpdateQueryLogging on this zone." or "Reading the query log needs
  dns:GetQueryLog on this zone."
- In the console, also `dns:ListZones` to open **Hosted zones** (without it the page shows an
  access-denied notice) and `dns:GetZone` to open the zone (without it the zone's page is not
  found).

## Turn query logging on

**Console**
1. Open the zone, then choose the **Query log** tab.
2. Under **Query logging is off**, choose **Turn on**.

The console says "Query logging is on." **Turn off** turns it off again.

**CLI**
```sh
dcloud dns query-log set zone-id --enabled
```

**API**
```http
PUT /dns/api/zones/zone-id/query-logging
{ "enabled": true }
```

**Terraform**
```hcl
resource "dcloud_dns_query_log" "main" {
  zone_id = dcloud_dns_zone.main.id
  enabled = true
}
```

Destroying the resource turns logging off.

The nameservers start logging on their next pull.

## Read the log

**Console**
1. Open the zone, then choose the **Query log** tab.

**Recent queries** lists the last hour, at most 200 lines, newest first, with **When**,
**Nameserver** and **Query**. Search them with the box above the table. With no lines in that hour
it says "No queries logged in the last hour."

**CLI**
```sh
dcloud dns query-log get zone-id --minutes 60 --contains NXDOMAIN
```

**API**
```http
GET /dns/api/zones/zone-id/query-log?minutes=60&contains=NXDOMAIN
```

`minutes` is 1 to 10080 (default 60), `limit` 1 to 1000 lines (default 200), and `contains` keeps
only lines with that text, ignoring case. The answer is `{ queryLogging, lines }`, each line `{ at, nameserver,
line }`, newest first.

**Terraform:** not available. Terraform does not read logs.

## Related

- [Monitoring](monitoring.md)
- [Security](security.md)
- `dns.query-log.set` · `dns.query-log.get` · `dcloud dns query-log set` ·
  `dcloud_dns_query_log`
