# Ship Kubernetes logs with the Tailcove agent

The kubelet already writes every container's stdout and stderr to files under `/var/log/pods` on each node. The
Tailcove agent runs as a DaemonSet, one pod per node, reads those files and sends each line with the namespace, pod
and container it came from. It also reports CPU and memory for every container and pod on the node. Your apps don't
change: if a container logs to stdout, it reaches Tailcove.

This guide installs the agent from our manifest, checks the first lines, then splits some namespaces into their own
sources, joins stack traces and sets up searches and alerts.

## 1. Create a source and store its token

Create a source in Tailcove for the cluster, for example `k8s-production`, and copy its ingest token. It's shown
once.

The agent reads the token from a Secret called `tailcove-agent`, under the key `token`, in the `tailcove`
namespace. Create both:

```bash
kubectl create namespace tailcove
kubectl -n tailcove create secret generic tailcove-agent --from-literal=token=YOUR_INGEST_TOKEN
```

## 2. Apply the manifest

```bash
kubectl apply -f https://tailcove.dev/agent/tailcove-agent.yaml
```

That one file creates everything in the `tailcove` namespace:

| Object | What it's for |
| ------ | ------------- |
| ServiceAccount, ClusterRole and ClusterRoleBinding `tailcove-agent` | Lets the agent get, list and watch pods, and nothing else. It never reads secrets or config maps, never fetches logs through the API and never execs. |
| ConfigMap `tailcove-agent` | The agent's settings (`agent.json`), everything but the token. |
| DaemonSet `tailcove-agent` | One agent per node, image `ghcr.io/tailcove/agent:0.3.0`, requesting 50m CPU and 64Mi of memory, limited to 500m and 256Mi. |

The DaemonSet tolerates every taint, so it lands on every node, control plane included. It runs as root because
the kubelet writes pod logs as root with mode 0640, but it drops every capability, can't escalate, has a read-only
root filesystem and mounts `/var/log/pods`, `/var/log/containers`, `/sys/fs/cgroup` and `/proc` read-only. The one
writable path is `/var/lib/tailcove-agent` on the node, where it keeps how far it got in each file.

Check that a pod is running on each node:

```bash
kubectl -n tailcove get pods -o wide
```

> [!TIP]
> To change the resources, the tolerations or the settings, download the file, edit it and apply your copy:
> `curl -fsSLO https://tailcove.dev/agent/tailcove-agent.yaml`, then `kubectl apply -f tailcove-agent.yaml`.

## 3. See the first lines

Look at what the agent says when it starts:

```bash
kubectl -n tailcove logs daemonset/tailcove-agent
```

You want a line like `kubernetes: node worker-1, /var/log/pods/*/*/*.log, host from the pod, with pod labels and
owners from the API, 0 route(s)`. Then open the source's [Live tail](https://tailcove.dev/docs/live-tail) and start something that
prints:

```bash
kubectl run hello --image=busybox --restart=Never -- sh -c 'echo hello from a pod'
```

The line shows up within a few seconds. A file that already existed when the agent first saw it is followed from
its end, so you won't get a flood of old lines on install (`from_beginning: true` changes that). A pod that
restarts writes a new file, and that one is read from its start.

Open the line and you'll see its context:

```json
{
    "kubernetes": {
        "namespace": "default",
        "pod": "hello",
        "container": "hello",
        "node": "worker-1",
        "restarts": 0
    },
    "stream": "stdout"
}
```

For a pod a Deployment, StatefulSet, DaemonSet or Job owns, `kubernetes` also has `workload`, the owner's name,
and `labels`, the pod labels you keep. By default those are `app`, `app.kubernetes.io/name`,
`app.kubernetes.io/component` and `app.kubernetes.io/version`. The line's `host` is the pod's name.

A line your app already writes as a JSON object is sent as it is: its own fields stay, and the agent adds the host,
a time if it has none, and the `kubernetes` object to its `context`. So a JSON logger that writes `level` gives you
`level:error` searches for free. A plain text line has no level; Tailcove only knows what the line says.

> [!NOTE]
> The manifest leaves out `kube-system` (`"exclude_namespaces": ["kube-system"]`). Remove that line from the
> ConfigMap if you want those pods too.

## 4. Change the settings

Everything below goes in the `kubernetes` block of `agent.json` in the ConfigMap. This is what the manifest ships:

```json
{
  "kubernetes": {
    "enabled": true,
    "host": "pod",
    "exclude_namespaces": ["kube-system"],
    "multiline": { "mode": "auto" },
    "metrics": { "enabled": true, "max_series": 500 }
  }
}
```

The agent reads its config when it starts, so restart the pods after you change it:

```bash
kubectl apply -f tailcove-agent.yaml
kubectl -n tailcove rollout restart daemonset/tailcove-agent
```

The settings you're most likely to touch:

| Setting | What it does | Default |
| ------- | ------------ | ------- |
| `host` | What a line's `host` is: `pod`, `node`, `workload` or `label:<key>` | `pod` |
| `labels` | Pod labels kept in the context (at most 10) | `app`, `app.kubernetes.io/name`, `/component`, `/version` |
| `include_namespaces` / `exclude_namespaces` | Namespace globs to keep or leave out | all |
| `exclude_pods` / `exclude_containers` | Pod and container name globs to leave out | none |
| `from_beginning` | Read files that were already there from their first line | `false` |
| `api` | Set `false` to skip the Kubernetes API; lines then carry only what the file path says (namespace, pod, container) | `true` |

Each one also has an environment variable, listed in the [agent reference](https://tailcove.dev/docs/sending-logs/agent), if you'd
rather set it on the DaemonSet.

`"host": "workload"` is worth a look. With the default, every new pod is a new host name, like
`checkout-7d9f8c6b5d-x2x9k`. With `workload`, all of a Deployment's pods log as `checkout`, which reads better in
search and in the host list.

## 5. Send some namespaces to their own sources

One cluster often holds more than one team's apps. A route sends the pods it matches to another source, with that
source's own token, so the billing team gets a `billing` source with only its own lines, its own retention and its
own alerts.

Create the second source in Tailcove, copy its token, and add `routes`:

```json
{
  "kubernetes": {
    "enabled": true,
    "host": "workload",
    "exclude_namespaces": ["kube-system"],
    "routes": [
      { "namespace": "billing", "token": "BILLING_SOURCE_TOKEN" },
      { "namespace": "payments-*", "token": "BILLING_SOURCE_TOKEN" },
      { "labels": { "team": "search" }, "token": "SEARCH_SOURCE_TOKEN" }
    ],
    "multiline": { "mode": "auto" },
    "metrics": { "enabled": true, "max_series": 500 }
  }
}
```

How routes are matched:

- `namespace` is a glob. `labels` must all be on the pod. A route with both needs both.
- The first route that matches wins. A pod no route matches goes to the main source, the one in the Secret.
- A route must name a namespace or labels. One that would match everything is refused at start-up, because that's
  what the main token is for.
- A namespace you exclude isn't sent anywhere, routes included.

Each routed source has its own queue. If one of its tokens is refused, that source's lines are dropped with one log
line and read again after a restart, and every other source keeps going.

> [!WARNING]
> Route tokens sit in `agent.json`, so anyone who can read config maps in the `tailcove` namespace can read them.
> If that's too wide, keep `agent.json` in a Secret instead: change the `config` volume in the DaemonSet from
> `configMap` to `secret` with the same name and key.

## 6. Join stack traces

A Java or Python stack trace is many lines on stdout. With `"multiline": {"mode": "auto"}`, which the manifest
sets, the agent glues indented lines and the usual trace lines (`Caused by:`, `... 12 more`, PHP `#3` frames, a
Python `Traceback`) to the line before them, so one exception is one entry in Tailcove. A line that starts with `{`
always begins a new event, so JSON logs are never merged.

If your logs start every event with something you can match, say a date, use a pattern instead:

```json@Pattern
{
  "kubernetes": {
    "multiline": { "mode": "pattern", "pattern": "^\\d{4}-\\d{2}-\\d{2}" }
  }
}
```

```json@Off
{
  "kubernetes": {
    "multiline": { "mode": "off" }
  }
}
```

With `pattern`, a line that matches starts a new event and every other line joins the one before. `off` sends every
line on its own. An event is cut at 200 lines or 64 KiB, or sent once a second passes without another line;
`max_lines`, `max_bytes` and `timeout_ms` change those. When the container runtime splits a very long line into
pieces, the agent joins them back whatever the mode.

## 7. Search by pod, workload and namespace

The search bar reads top-level fields of `context` and the `host` and `level` columns. The pod details sit one level
down, inside `kubernetes`, so `kubernetes.namespace:billing` isn't a field search: the dot makes it plain text,
looked for in the message. Here's what does work:

```
host:checkout-*                       → every pod of the checkout Deployment (host is the pod)
host:checkout level:error             → errors from the checkout workload ("host": "workload")
stream:stderr                         → what plain-text containers wrote to stderr
kubernetes:*                          → every line that came from a pod
```

`host:` takes a trailing `*` as "starts with", which suits pod names. There's no direct search for a namespace yet,
because it sits inside the `kubernetes` object. To search one namespace, give it a handle of its own:

- Route it to its own source (step 5). Then every search on that source is already that namespace.
- Set `"host": "label:app"` (or another label you set on every pod) so `host:` filters on it.
- Have your app log JSON with its own top-level fields, such as `service` or `tenant`. Those are fields the search
  reads straight away.

## 8. Chart container metrics

With `metrics.enabled` on, every 30 seconds the agent reads cgroups (v2 or v1) and reports, labelled with the
namespace, pod and container:

| Metric | What it is |
| ------ | ---------- |
| `container.cpu.usage_cores` | CPU in use, in cores |
| `container.cpu.usage_seconds_total` | CPU time used |
| `container.cpu.throttled_seconds_total` | Time the container was throttled by its CPU limit |
| `container.cpu.limit_cores` | The CPU limit |
| `container.memory.working_set_bytes` | Working set memory |
| `container.memory.usage_bytes` | Memory usage |
| `container.memory.limit_bytes` | The memory limit |
| `container.memory.oom_kills_total` | OOM kills |
| `pod.cpu.usage_cores`, `pod.memory.working_set_bytes` | The same for the whole pod |

They're on the source's **Metrics** tab. A counter (the `_total` ones) is best charted with `max` or `last`.

Every distinct container is a series, and series count toward your plan's [limit](https://tailcove.dev/docs/metrics/overview): 100 on
Free, 1,000 on Pro, 5,000 on Business. `max_series` (500 in the manifest) caps one reading, pods first. When it cuts
points, the agent logs `kubernetes metrics: N point(s) left out to keep to max_series 500`. Raise it, or exclude
namespaces you don't need, and keep it under your plan's limit.

## 9. Alert on it

A log alert uses the same query language. On the source's **Alerts** tab, create one with:

| Field | Value |
| ----- | ----- |
| Query | `host:checkout level:error` |
| Threshold | `10` |
| Window | `5` |

That fires when the checkout pods log 10 or more errors in 5 minutes. A routed source gets its own alerts and its own
channels, which is often the reason to route it. [Alert on error spikes](https://tailcove.dev/guides/alert-on-error-spikes) goes
further.

For a metric alert, choose **A metric**, enter `container.memory.working_set_bytes`, aggregate `max`, above
`1610612736` (1.5 GiB). With the host left blank it fires when any one container crosses it.

The agent also sends a heartbeat, `system.agent.up`, every 30 seconds. The source's **Overview** lists each agent
with **Beating** or **Quiet**, and **Alert if it goes quiet** fills in a [no-data alert](https://tailcove.dev/docs/alerts) for it.
Inside a pod, the agent's host name is its own pod name (`tailcove-agent-x7k2p`), which changes whenever the pod is
replaced. To name agents after their nodes instead, add this to the DaemonSet's `env`:

```yaml
- name: TAILCOVE_HOST
  valueFrom:
    fieldRef:
      fieldPath: spec.nodeName
```

That sets the host of the heartbeat and the metrics. Log lines keep the host from the `host` setting.

## If nothing arrives

| What you see | What it means and what to do |
| ------------ | ---------------------------- |
| Agent pod stuck in `CreateContainerConfigError` | The Secret is missing or has no `token` key. Create `tailcove-agent` in the `tailcove` namespace with `--from-literal=token=...`. |
| `the API answered HTTP 401` in the agent's log | The token is wrong or belongs to another source. Copy it again, recreate the Secret, then restart the DaemonSet. |
| A route's lines never show up | That route's token is refused. Its lines are dropped with a log line while every other source carries on. Fix the token and restart. |
| `kubernetes: could not list the pods on ...` | The ServiceAccount can't list pods: the ClusterRole or its binding is missing. Lines still arrive, with namespace, pod and container from the file path but no labels or workload. Re-apply the manifest. |
| `kubernetes: the node name is unknown` | `NODE_NAME` was removed from the DaemonSet. Put back the `spec.nodeName` field reference. |
| Agent pod won't start, with a mount error for `/var/log/pods` | The node keeps pod logs somewhere else. The manifest expects the kubelet's standard `/var/log/pods` and `/var/log/containers`. |
| Some namespace never shows up | Check `include_namespaces` and `exclude_namespaces`. The manifest excludes `kube-system`. |
| Old lines are missing after install | Files already there are followed from their end. Set `from_beginning: true` if you want them. |
| `kubernetes: ignoring the multiline setting` | The multiline block is invalid, for example `pattern` mode with no pattern. Fix it and restart. |
| `429` in the agent's log | You're over your plan's rate. The agent waits and retries; check your usage on the Billing page. |

A line can arrive twice after the agent restarts. That's on purpose: it records how far it got only after Tailcove
accepted the batch, so a restart repeats a line rather than loses one.

## Next steps

- Every setting and environment variable: the [agent reference](https://tailcove.dev/docs/sending-logs/agent).
- More on searching: the [query language](https://tailcove.dev/docs/query-language).
- Not on Kubernetes? [Forward Docker container logs with Fluent Bit](https://tailcove.dev/guides/fluent-bit-docker-logs).
