> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 ClickHouse Observability 监控 EC2 主机日志

> 使用 OpenTelemetry 收集 EC2 syslog 文件，并在 ClickHouse Observability 中借助实例元数据为其补充信息。

使用 OpenTelemetry 采集器收集 EC2 syslog 日志文件，并连同实例元数据一并发送到 ClickHouse Observability。即使没有 EC2 实例，也可以使用[演示数据集](#demo-dataset)试用此集成。

## 前置条件

* 一个 ClickHouse Observability 服务
* 如需采集您自己的日志：一台包含 syslog 文件的 Linux EC2 实例，该实例能够访问其实例元数据服务，且您拥有安装并运行采集器的权限
* 如需运行演示：Docker
* `curl`，用于下载采集器或样本数据

### 连接详情

> [tab] 全托管
>
> [Beta 服务](https://clickhouse.com/docs/reference/settings/beta-and-experimental-features.md#beta-features)
>
> 打开 ClickHouse Observability，进入 **团队设置 → 数据 → Managed Telemetry**，复制您的 OTLP HTTP 端点和 API key。您可以点击 **Copy connection details** 复制配置，或点击 **Reveal key** 查看已隐藏的 key。
>
> ![Managed Telemetry 连接详情](https://mintcdn.com/private-7c7dfe99/Zk1feNn6fCQBpold/images/clickstack/getting-started/observability-managed-telemetry.png?fit=max\&auto=format\&n=Zk1feNn6fCQBpold\&q=85\&s=e63a2ac2e6ab996d3fc360ebe0f487a5)
>
> 为配合下方的 OTLP 导出器示例，请在将要运行采集器的终端中设置以下变量：
>
> ```bash theme={null}
> export OTEL_EXPORTER_OTLP_ENDPOINT='https://YOUR_OTEL_ENDPOINT:4318'
> export OTEL_EXPORTER_OTLP_AUTHORIZATION='Bearer YOUR_API_KEY'
> ```
>
> 将占位符替换为您服务的实际端点 (包括端口) 和 API key。请使用不带 `/v1/logs` 后缀的基础 HTTP 端点，导出器会自动追加信号路径。

> [tab] 自管理
>
> 使用采集器可访问的 OTLP HTTP 端点 (例如 `http://YOUR_COLLECTOR_HOST:4318`) 及相应的身份验证设置。如果您的采集器无需身份验证，请在下方配置中省略导出器的 `headers` 块。有关设置说明，请参阅[自管理入门指南](https://clickhouse.com/docs/zh/clickstack/self-configured/getting-started/managed.md)。
>
> ```bash theme={null}
> export OTEL_EXPORTER_OTLP_ENDPOINT='http://YOUR_COLLECTOR_HOST:4318'
> export OTEL_EXPORTER_OTLP_AUTHORIZATION='YOUR_INGESTION_KEY'
> ```

您的 EC2 实例必须能够访问该端点。在 Docker 演示中，运行在您本机上的目标端采集器可通过 `http://host.docker.internal:4318` 访问；演示命令中已包含相应的主机映射。

## 与现有 EC2 实例集成

在需要采集日志的 EC2 实例上执行以下步骤。

**1. 检查实例元数据和 syslog**

请确认可以通过 IMDSv2 访问实例元数据服务：

```bash theme={null}
TOKEN=$(curl -fsS --connect-timeout 5 -X PUT \
  -H 'X-aws-ec2-metadata-token-ttl-seconds: 300' \
  http://169.254.169.254/latest/api/token)
curl -fsS --connect-timeout 5 -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/instance-id
```

响应中应包含您的实例 ID。采集器会通过此元数据服务，为您的日志添加实例 ID、实例类型、区域、可用区和账户 ID。以下配置不会采集 EC2 标签。

找到您的 syslog 文件并查看其格式：

```bash theme={null}
# Ubuntu/Debian
tail -20 /var/log/syslog

# Amazon Linux/RHEL
tail -20 /var/log/messages
```

请使用您实例上实际存在的路径。如果日志仅写入 systemd 系统日志，请参阅 [Systemd/Journald 指南](https://clickhouse.com/docs/zh/clickstack/observability/integration-examples/systemd.md) 进行采集。

**2. 安装采集器**

请根据您实例的架构下载 OpenTelemetry Collector Contrib `0.161.0`：

```bash theme={null}
case "$(uname -m)" in
  x86_64) ARCH=amd64 ;;
  aarch64) ARCH=arm64 ;;
  *) echo "Unsupported architecture"; exit 1 ;;
esac
curl -fLO "https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.161.0/otelcol-contrib_0.161.0_linux_${ARCH}.tar.gz"
tar -xzf "otelcol-contrib_0.161.0_linux_${ARCH}.tar.gz" otelcol-contrib
sudo install -m 755 otelcol-contrib /usr/local/bin/otelcol-contrib
/usr/local/bin/otelcol-contrib --version
```

**3. 配置采集器**

将相应的配置保存为 `ec2-host-logs.yaml`。请根据文件中的时间戳格式选择对应配置；如果您的 syslog 路径与示例不同，请相应调整 `include`。

> [tab] ISO 时间戳
>
> 适用于 `2026-10-15T12:34:56.123456+00:00` 这类时间戳：
>
> ```yaml theme={null}
> receivers:
>   filelog/ec2:
>     include: [/var/log/syslog]
>     start_at: end
>     operators:
>       - type: regex_parser
>         regex: '^(?P<timestamp>\S+) (?P<hostname>\S+) (?P<unit>\S+?)(?:\[(?P<pid>\d+)\])?: (?P<message>.*)$'
>         timestamp:
>           parse_from: attributes.timestamp
>           layout_type: gotime
>           layout: '2006-01-02T15:04:05.999999999Z07:00'
>           location: UTC
>       - type: add
>         field: attributes.source
>         value: ec2-host-logs
>       - type: add
>         field: resource["service.name"]
>         value: ec2-host-service
>       - type: copy
>         from: attributes.hostname
>         to: resource["host.name"]
>
> processors:
>   memory_limiter:
>     check_interval: 1s
>     limit_mib: 256
>     spike_limit_mib: 64
>   resourcedetection/ec2:
>     detectors: [ec2]
>     timeout: 5s
>     override: false
>   batch:
>     timeout: 5s
>     send_batch_size: 500
>     send_batch_max_size: 500
>
> exporters:
>   otlp_http/observability:
>     endpoint: ${env:OTEL_EXPORTER_OTLP_ENDPOINT}
>     headers:
>       authorization: ${env:OTEL_EXPORTER_OTLP_AUTHORIZATION}
>
> service:
>   pipelines:
>     logs/ec2:
>       receivers: [filelog/ec2]
>       processors: [memory_limiter, resourcedetection/ec2, batch]
>       exporters: [otlp_http/observability]
> ```

> [tab] 传统 syslog
>
> 适用于 `Oct 15 12:34:56` 这类时间戳：
>
> ```yaml theme={null}
> receivers:
>   filelog/ec2:
>     include: [/var/log/messages]
>     start_at: end
>     operators:
>       - type: regex_parser
>         regex: '^(?P<timestamp>\w+\s+\d+ \d{2}:\d{2}:\d{2}) (?P<hostname>\S+) (?P<unit>\S+?)(?:\[(?P<pid>\d+)\])?: (?P<message>.*)$'
>         timestamp:
>           parse_from: attributes.timestamp
>           layout_type: gotime
>           layout: 'Jan _2 15:04:05'
>           location: UTC
>       - type: add
>         field: attributes.source
>         value: ec2-host-logs
>       - type: add
>         field: resource["service.name"]
>         value: ec2-host-service
>       - type: copy
>         from: attributes.hostname
>         to: resource["host.name"]
>
> processors:
>   memory_limiter:
>     check_interval: 1s
>     limit_mib: 256
>     spike_limit_mib: 64
>   resourcedetection/ec2:
>     detectors: [ec2]
>     timeout: 5s
>     override: false
>   batch:
>     timeout: 5s
>     send_batch_size: 500
>     send_batch_max_size: 500
>
> exporters:
>   otlp_http/observability:
>     endpoint: ${env:OTEL_EXPORTER_OTLP_ENDPOINT}
>     headers:
>       authorization: ${env:OTEL_EXPORTER_OTLP_AUTHORIZATION}
>
> service:
>   pipelines:
>     logs/ec2:
>       receivers: [filelog/ec2]
>       processors: [memory_limiter, resourcedetection/ec2, batch]
>       exporters: [otlp_http/observability]
> ```
>
> 传统时间戳不包含年份和时区信息。解析器会自动推断年份；如果您的主机不使用 UTC 记录日志，请将 `location` 设置为该主机所在的 IANA 时区。

该接收器会保留原始日志行，并从中提取主机名、unit、PID (如有) 和消息。`resourcedetection/ec2` 处理器会添加 EC2 资源属性。如需同时采集实例标签，请参阅 [EC2 检测器配置](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/v0.161.0/processor/resourcedetectionprocessor#aws-ec2)及其权限要求。

**4. 运行采集器**

在此终端中设置[连接变量](#connection-details)，然后在配置文件所在的目录中运行。采集器需要具备读取 syslog 文件的权限：

```bash theme={null}
sudo --preserve-env=OTEL_EXPORTER_OTLP_ENDPOINT,OTEL_EXPORTER_OTLP_AUTHORIZATION \
  /usr/local/bin/otelcol-contrib --config="$(pwd)/ec2-host-logs.yaml"
```

请保持终端处于打开状态。该接收器使用 `start_at: end`，因此需要在启动后产生新的活动，使其写入 syslog 文件。如需持续采集，请按照您的部署流程配置一个服务，并将连接变量提供给该服务。

**5. 检查日志**

打开 **搜索** 页面，选择你的 **Logs** source，按 `ServiceName:ec2-host-service` 进行过滤，并选择 **Last 15 minutes**。展开任意一条记录，查看其资源属性中的 `cloud.provider`、`cloud.region`、`cloud.availability_zone`、`host.id` 和 `host.type`。

## 演示数据集

该样本数据包含 11,658 条 syslog 日志行，时间跨度为 24 小时。采集器会添加模拟的 EC2 元数据并刷新时间戳，因此无需 AWS 账户。

**1. 下载示例数据**

```bash theme={null}
mkdir -p ec2-demo
cd ec2-demo
curl -fLO https://datasets-documentation.s3.eu-west-3.amazonaws.com/clickstack-integrations/host-logs/journal.log
```

**2. 配置演示采集器**

将以下内容另存为下载目录中的 `ec2-host-logs-demo.yaml`：

```yaml theme={null}
receivers:
  filelog/ec2:
    include: [/var/log/host/journal.log]
    start_at: beginning
    operators:
      - type: regex_parser
        regex: '^(?P<timestamp>\S+) (?P<hostname>\S+) (?P<unit>\S+?)(?:\[(?P<pid>\d+)\])?: (?P<message>.*)$'
        timestamp:
          parse_from: attributes.timestamp
          layout: '%Y-%m-%dT%H:%M:%S%z'
          location: UTC
      - type: add
        field: attributes.source
        value: ec2-demo
      - type: add
        field: resource["service.name"]
        value: ec2-demo
      - type: copy
        from: attributes.hostname
        to: resource["host.name"]

processors:
  memory_limiter:
    check_interval: 1s
    limit_mib: 256
    spike_limit_mib: 64
  transform/demo_timestamps:
    error_mode: propagate
    log_statements:
      - context: log
        statements:
          - set(time, Now() - Duration("2m") - (Time("2025-11-11T23:59:01Z", "%Y-%m-%dT%H:%M:%SZ") - time))
  resource/ec2_demo:
    attributes:
      - key: cloud.provider
        value: "aws"
        action: insert
      - key: cloud.platform
        value: "aws_ec2"
        action: insert
      - key: cloud.region
        value: "us-east-1"
        action: insert
      - key: cloud.availability_zone
        value: "us-east-1a"
        action: insert
      - key: host.id
        value: "i-0abc123def456789"
        action: insert
      - key: host.type
        value: "t3.medium"
        action: insert
  batch:
    timeout: 5s
    send_batch_size: 500
    send_batch_max_size: 500

exporters:
  otlp_http/observability:
    endpoint: ${env:OTEL_EXPORTER_OTLP_ENDPOINT}
    headers:
      authorization: ${env:OTEL_EXPORTER_OTLP_AUTHORIZATION}

service:
  pipelines:
    logs/ec2:
      receivers: [filelog/ec2]
      processors: [memory_limiter, resource/ec2_demo, transform/demo_timestamps, batch]
      exporters: [otlp_http/observability]
```

> [!NOTE]
>
> 此时间戳转换仅用于演示，会将样本数据平移到大约过去 24 小时的时间范围内，截止于摄取前两分钟。如需处理您自己的日志，请使用 [EC2 实例配置](#existing-ec2)，以保留其原始时间戳。

**3. 运行演示采集器**

设置好[连接变量](#connection-details)后，在下载目录中运行以下命令：

```bash theme={null}
docker run --rm --name ec2-demo-collector \
  --add-host=host.docker.internal:host-gateway \
  --memory=512m \
  -e OTEL_EXPORTER_OTLP_ENDPOINT \
  -e OTEL_EXPORTER_OTLP_AUTHORIZATION \
  -v "$(pwd)/ec2-host-logs-demo.yaml:/etc/otelcol-contrib/config.yaml:ro" \
  -v "$(pwd):/var/log/host:ro" \
  otel/opentelemetry-collector-contrib:0.161.0 \
  --config=/etc/otelcol-contrib/config.yaml
```

在采集器导出示例数据期间，请保持终端打开，并检查终端输出中是否有错误。如果再次启动新容器，可能会导致示例日志重复。

**4. 验证演示日志**

打开 **搜索** 页面，选择你的 **Logs** source，按 `ServiceName:ec2-demo` 进行过滤，并选择 **Last 2 days**。展开一条日志，查看模拟的资源属性：`cloud.region` 为 `us-east-1`，`host.id` 为 `i-0abc123def456789`，`host.type` 为 `t3.medium`。确认数据无误后，按 **Ctrl+C** 停止采集器。

![ClickHouse Observability 搜索页面中的 EC2 演示日志](https://mintcdn.com/private-7c7dfe99/dW6bcEakZdn3a5oP/images/clickstack/observability-ec2-demo-logs.png?fit=max\&auto=format\&n=dW6bcEakZdn3a5oP\&q=85\&s=db20aac2ee4ef9737e4d34a432100469)

## 仪表盘与可视化

**1. [下载仪表盘配置](https://clickhouse-docs-assets.s3.us-east-1.amazonaws.com/examples/host-logs-dashboard.json)**

**2. 导入仪表盘**

1. 打开 **Dashboards**，然后点击右上角的 **Import**。
2. 上传 `host-logs-dashboard.json`。
3. 将图表映射到您的 **Logs** source，然后点击 **Finish Import**。

![导入仪表盘按钮](https://mintcdn.com/private-7c7dfe99/dW6bcEakZdn3a5oP/images/clickstack/observability-import-dashboard.png?fit=max\&auto=format\&n=dW6bcEakZdn3a5oP\&q=85\&s=16bcb7e6365ca0f6decac5c693e228eb)

**3. 查看仪表盘**

导入的仪表盘会显示所选时间范围内的日志。如需将样本数据与其他服务区分开，可使用 `ServiceName:ec2-demo` 过滤器 (可选) 。选择 **Last 2 days** 即可查看完整的样本数据。您还可以使用 EC2 资源属性过滤器，例如 `ResourceAttributes.cloud.region:us-east-1` 或 `ResourceAttributes.host.id:i-0abc123def456789`。

该仪表盘涵盖日志量、系统单元、SSH 活动、防火墙拦截和服务重启等内容。除非摄取管道提供严重级别 (Severity) ，否则该字段为空。

![ClickHouse Observability 中的主机日志仪表盘](https://mintcdn.com/private-7c7dfe99/dW6bcEakZdn3a5oP/images/clickstack/observability-ec2-dashboard.png?fit=max\&auto=format\&n=dW6bcEakZdn3a5oP\&q=85\&s=e58730e1639e4c411173209cc4c80eec)

> [!NOTE]
>
> 如果使用您的 EC2 服务过滤器后，SSH activity、Firewall blocks 或未命名的安全事件图表为空，请检查这些图表的聚合过滤器，若其中包含 `ServiceName = 'host-demo' AND`，请将其删除。然后使用仪表盘的服务名称过滤器选择您的 EC2 日志。

## 故障排查

### EC2 元数据缺失

在 EC2 实例上运行元数据检查。确保 IMDS 已启用，且本地防火墙或 proxy 设置允许向 `169.254.169.254` 发送请求。如果使用了 proxy，请通过 `NO_PROXY` 排除该地址。检查采集器输出中是否存在元数据检测错误。该演示使用模拟元数据，不会访问 IMDS。

### 未显示日志

* 确认 `include` 中的路径存在，且采集器有权限读取该路径。
* 采集器启动后需生成新的日志条目，因为 `start_at: end` 会跳过已有内容。
* 检查采集器输出中是否有身份验证或导出错误，并确认从该实例可以访问该端点。
* 核实 **Logs** source、服务名称过滤器和时间范围是否正确。本演示请使用 **Last 2 days**。

### 日志未能正确解析

请将文件中的时间戳与所选配置进行核对。对于传统 syslog，请设置正确的主机时区。仅采集与已配置格式相匹配的文件。

## 后续步骤

* 为身份验证失败或服务错误设置[告警](https://clickhouse.com/docs/zh/clickstack/observability/features/alerts.md)。
* 按 EC2 资源属性进行过滤，以排查特定实例或区域的问题。
* 有关部署指南，请参阅[发送 OpenTelemetry 数据](https://clickhouse.com/docs/zh/clickstack/observability/ingesting-data/opentelemetry.md)。
