# Loki Logger

`loki-logger` 插件将网关的请求和响应日志分批发送至 [Grafana Loki](https://grafana.com/oss/loki/)，并通过 [Loki HTTP API](https://grafana.com/docs/loki/latest/reference/loki-http-api/#ingest-logs) 完成传输。插件会将每条日志序列化为 JSON，并支持自定义日志字段和标签。通过此集成，可以集中管理网关日志，并在 Grafana 中查询和可视化日志。

## 示例[​](#示例 "示例的直接链接")

以下示例展示了如何针对常见的日志记录场景配置 `loki-logger` 插件。

要跟随示例操作，请先启动 Loki 和 Grafana。在 Docker 环境中，网关、Loki 和 Grafana 共用一个专用网络，以便各容器可以通过名称互相访问。

以下 Loki 和 Grafana 部署仅用于评估。在生产环境中，请遵循 Grafana 的 [Loki 部署指南](https://grafana.com/docs/loki/latest/get-started/deployment-modes/)和 [Grafana 安全指南](https://grafana.com/docs/grafana/latest/setup-grafana/configure-security/)。

* Docker
* Kubernetes

将 `GATEWAY_CONTAINER` 设置为正在运行的 APISIX 或 API7 网关容器名称。创建一个专用 Docker 网络，并将网关连接到该网络：

```
export GATEWAY_CONTAINER=replace-with-gateway-container-name



docker network create gateway-loki-net

docker network connect gateway-loki-net "$GATEWAY_CONTAINER"
```

下载与固定 Loki 版本相匹配的配置：

```
curl -fsSL \

  "https://raw.githubusercontent.com/grafana/loki/v3.7.6/cmd/loki/loki-local-config.yaml" \

  -o loki-config.yaml
```

在共享网络中启动 Loki：

```
docker run -d \

  --name loki \

  --network gateway-loki-net \

  -v "$PWD/loki-config.yaml:/etc/loki/local-config.yaml:ro" \

  -p 127.0.0.1:3100:3100 \

  grafana/loki:3.7.6 \

  -config.file=/etc/loki/local-config.yaml
```

等待 Loki 就绪：

```
until curl -fsS "http://127.0.0.1:3100/ready" > /dev/null; do

  sleep 2

done
```

在同一网络中启动 Grafana：

```
docker run -d \

  --name grafana \

  --network gateway-loki-net \

  -p 127.0.0.1:3000:3000 \

  grafana/grafana:13.2.1
```

打开 [`http://localhost:3000`](http://localhost:3000) 访问 Grafana，并使用初始用户名和初始密码 `admin` 登录。前往 **Connections → Add new connection**，选择 Loki 并添加新的数据源。将 URL 设置为 `http://loki:3100`，选择 **Save & test**，并确认连接成功。

为 Loki、Grafana 和 Grafana 数据源创建 Kubernetes 清单：

loki-deployment.yaml

```
apiVersion: v1

kind: ConfigMap

metadata:

  namespace: aic

  name: loki-config

data:

  loki-config.yaml: |

    auth_enabled: false

    server:

      http_listen_port: 3100

      grpc_listen_port: 9096

    common:

      instance_addr: 127.0.0.1

      path_prefix: /tmp/loki

      storage:

        filesystem:

          chunks_directory: /tmp/loki/chunks

          rules_directory: /tmp/loki/rules

      replication_factor: 1

      ring:

        kvstore:

          store: inmemory

    schema_config:

      configs:

        - from: 2020-10-24

          store: tsdb

          object_store: filesystem

          schema: v13

          index:

            prefix: index_

            period: 24h

    query_range:

      results_cache:

        cache:

          embedded_cache:

            enabled: true

            max_size_mb: 100

    limits_config:

      metric_aggregation_enabled: true

      enable_multi_variant_queries: true

    pattern_ingester:

      enabled: true

      metric_aggregation:

        loki_address: localhost:3100

    ruler:

      alertmanager_url: http://localhost:9093

    frontend:

      encoding: protobuf

---

apiVersion: apps/v1

kind: Deployment

metadata:

  namespace: aic

  name: loki

spec:

  replicas: 1

  selector:

    matchLabels:

      app: loki

  template:

    metadata:

      labels:

        app: loki

    spec:

      containers:

        - name: loki

          image: grafana/loki:3.7.6

          args:

            - -config.file=/mnt/config/loki-config.yaml

          ports:

            - containerPort: 3100

          readinessProbe:

            httpGet:

              path: /ready

              port: 3100

          volumeMounts:

            - name: config

              mountPath: /mnt/config

      volumes:

        - name: config

          configMap:

            name: loki-config

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: loki

spec:

  selector:

    app: loki

  ports:

    - port: 3100

      targetPort: 3100

---

apiVersion: v1

kind: ConfigMap

metadata:

  namespace: aic

  name: grafana-datasources

data:

  loki.yaml: |

    apiVersion: 1

    datasources:

      - name: Loki

        type: loki

        access: proxy

        url: http://loki.aic.svc:3100

        isDefault: true

---

apiVersion: apps/v1

kind: Deployment

metadata:

  namespace: aic

  name: grafana

spec:

  replicas: 1

  selector:

    matchLabels:

      app: grafana

  template:

    metadata:

      labels:

        app: grafana

    spec:

      containers:

        - name: grafana

          image: grafana/grafana:13.2.1

          ports:

            - containerPort: 3000

          readinessProbe:

            httpGet:

              path: /api/health

              port: 3000

          volumeMounts:

            - name: datasources

              mountPath: /etc/grafana/provisioning/datasources

      volumes:

        - name: datasources

          configMap:

            name: grafana-datasources

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: grafana

spec:

  selector:

    app: grafana

  ports:

    - port: 3000

      targetPort: 3000
```

将清单应用到集群：

```
kubectl apply -f loki-deployment.yaml
```

等待两个 Deployment 均就绪：

```
kubectl rollout status deployment/loki -n aic

kubectl rollout status deployment/grafana -n aic
```

在另一个终端中，将 Grafana Service 端口转发到本地计算机：

```
kubectl port-forward -n aic service/grafana 3000:3000
```

打开 [`http://localhost:3000`](http://localhost:3000) 访问 Grafana，并使用初始用户名和初始密码 `admin` 登录。预配置的 Loki 数据源使用集群内地址 `http://loki.aic.svc:3100`。

### 使用默认日志格式记录请求和响应[​](#使用默认日志格式记录请求和响应 "使用默认日志格式记录请求和响应的直接链接")

以下示例使用默认日志格式，记录经过某条路由的请求和响应。

创建一条启用 `loki-logger` 插件的路由，并配置 Loki 地址：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes/loki-logger-route" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -H "Content-Type: application/json" \

  -d '{

    "uri": "/anything",

    "plugins": {

      "loki-logger": {

        "endpoint_addrs": ["http://loki:3100"]

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - uris:

          - /anything

        name: loki-logger-route

        plugins:

          loki-logger:

            endpoint_addrs:

              - "http://loki:3100"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

ADC 会将标签选择器应用于本地服务，并仅协调带有相同标签的远端服务。预览限定范围内的变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=loki-logger
```

同步已审查的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=loki-logger
```

* Gateway API
* APISIX CRD

loki-logger-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: loki-logger-plugin-config

spec:

  plugins:

    - name: loki-logger

      config:

        endpoint_addrs:

          - "http://loki.aic.svc:3100"

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: loki-logger-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: loki-logger-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

loki-logger-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: loki-logger-route

spec:

  ingressClassName: apisix

  http:

    - name: loki-logger-route

      match:

        paths:

          - /anything

        methods:

          - GET

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: loki-logger

          config:

            endpoint_addrs:

              - "http://loki.aic.svc:3100"
```

应用配置：

```
kubectl apply -f loki-logger-ic.yaml
```

❶ `endpoint_addrs`：网关可以访问的 Loki 基础 URL。

向该路由发送几次请求以生成日志条目：

```
curl "http://127.0.0.1:9080/anything"
```

所有请求都应收到 `HTTP/1.1 200 OK` 响应。

打开 [Grafana Explore 页面](http://localhost:3000/explore)，并运行 LogQL 查询 `{job="apisix"}`。你应该会看到这些请求的日志条目，其中包含与以下内容类似的条目：

```
{

  "route_id": "loki-logger-route",

  "response": {

    "status": 200,

    "headers": {

      "date": "Wed, 16 Sep 2026 12:16:13 GMT",

      "server": "APISIX/3.18.0",

      "access-control-allow-credentials": "true",

      "content-length": "399",

      "access-control-allow-origin": "*",

      "content-type": "application/json",

      "connection": "close"

    },

    "size": 627

  },

  "start_time": 1789560971406,

  "client_ip": "192.168.155.1",

  "service_id": "",

  "apisix_latency": 1340.0001735687,

  "upstream": "34.198.63.32:80",

  "upstream_latency": 753,

  "server": {

    "hostname": "dd2886d0b7bf",

    "version": "3.18.0"

  },

  "request": {

    "headers": {

      "user-agent": "curl/8.7.1",

      "accept": "*/*",

      "host": "127.0.0.1:9080"

    },

    "size": 85,

    "method": "GET",

    "url": "http://127.0.0.1:9080/anything",

    "querystring": {},

    "uri": "/anything"

  },

  "latency": 2093.0001735687

}
```

这表明 Loki 已收到网关日志。你还可以创建 Grafana 仪表盘来可视化和分析这些日志。

### 使用插件元数据自定义日志格式[​](#使用插件元数据自定义日志格式 "使用插件元数据自定义日志格式的直接链接")

以下示例使用[插件元数据](https://docs.apiseven.com/apisix/key-concepts/plugin-metadata.md)，为所有未自行定义日志格式的 `loki-logger` 实例自定义日志格式。

创建一条启用 `loki-logger` 插件的路由：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes/loki-logger-route" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -H "Content-Type: application/json" \

  -d '{

    "uri": "/anything",

    "plugins": {

      "loki-logger": {

        "endpoint_addrs": ["http://loki:3100"]

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org": 1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - uris:

          - /anything

        name: loki-logger-route

        plugins:

          loki-logger:

            endpoint_addrs:

              - "http://loki:3100"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

ADC 会将标签选择器应用于本地服务，并仅协调带有相同标签的远端服务。预览本示例的变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=loki-logger
```

同步已审查的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=loki-logger
```

* Gateway API
* APISIX CRD

loki-logger-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: loki-logger-plugin-config

spec:

  plugins:

    - name: loki-logger

      config:

        endpoint_addrs:

          - "http://loki.aic.svc:3100"

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: loki-logger-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: loki-logger-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

loki-logger-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: loki-logger-route

spec:

  ingressClassName: apisix

  http:

    - name: loki-logger-route

      match:

        paths:

          - /anything

        methods:

          - GET

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: loki-logger

          config:

            endpoint_addrs:

              - "http://loki.aic.svc:3100"
```

应用配置：

```
kubectl apply -f loki-logger-ic.yaml
```

配置 `loki-logger` 的插件元数据，以设置共享日志格式：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/loki-logger" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -H "Content-Type: application/json" \

  -d '{

    "log_format": {

      "host": "$host",

      "client_ip": "$remote_addr",

      "route_id": "$route_id",

      "@timestamp": "$time_iso8601"

    }

  }'
```

导出完整的插件元数据集合：

```
adc dump -o adc.yaml --with-id --include-resource-type plugin_metadata
```

在导出的 `plugin_metadata` 映射中添加或更新此条目，保留所有其他条目：

adc.yaml (fragment)

```
plugin_metadata:

  loki-logger:

    log_format:

      host: "$host"

      client_ip: "$remote_addr"

      route_id: "$route_id"

      "@timestamp": "$time_iso8601"
```

预览完整的插件元数据集合，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml --include-resource-type plugin_metadata
```

同步已审查的插件元数据：

```
adc sync -f adc.yaml --include-resource-type plugin_metadata
```

gatewayproxy.yaml

```
apiVersion: apisix.apache.org/v1alpha1

kind: GatewayProxy

metadata:

  namespace: aic

  name: apisix-config

spec:

  provider:

    type: ControlPlane

    controlPlane:

      # ...

      # 你的控制面连接配置

  pluginMetadata:

    loki-logger:

      log_format:

        host: "$host"

        client_ip: "$remote_addr"

        route_id: "$route_id"

        "@timestamp": "$time_iso8601"
```

应用配置：

```
kubectl apply -f gatewayproxy.yaml
```

向该路由发送请求以生成新的日志条目：

```
curl -i "http://127.0.0.1:9080/anything"
```

你应该会收到 `HTTP/1.1 200 OK` 响应。

打开 [Grafana Explore 页面](http://localhost:3000/explore)，并运行 LogQL 查询 `{job="apisix"}`。你应该会看到与以下内容类似的条目：

```
{

  "@timestamp":"2026-09-16T12:16:38+00:00",

  "client_ip":"192.168.155.1",

  "route_id":"loki-logger-route",

  "host":"127.0.0.1"

}
```

如果路由上的插件指定了专用日志格式，该格式的优先级将高于插件元数据中指定的日志格式。例如，按以下方式更新上一条路由中的插件：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes/loki-logger-route" -X PATCH \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -H "Content-Type: application/json" \

  -d '{

    "plugins": {

      "loki-logger": {

        "log_format": {

          "route_id": "$route_id",

          "client_ip": "$remote_addr",

          "@timestamp": "$time_iso8601"

        }

      }

    }

  }'
```

更新 `adc.yaml`，向 `loki-logger` 插件添加路由级别的 `log_format`：

adc.yaml

```
services:

  - name: httpbin

    routes:

      - uris:

          - /anything

        name: loki-logger-route

        plugins:

          loki-logger:

            endpoint_addrs:

              - "http://loki:3100"

            log_format:

              route_id: "$route_id"

              client_ip: "$remote_addr"

              "@timestamp": "$time_iso8601"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览限定范围内的服务变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=loki-logger
```

同步已审查的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=loki-logger
```

* Gateway API
* APISIX CRD

更新 `loki-logger-ic.yaml`，为 `PluginConfig` 添加路由级 `log_format`：

loki-logger-ic.yaml

```
apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: loki-logger-plugin-config

spec:

  plugins:

    - name: loki-logger

      config:

        endpoint_addrs:

          - "http://loki.aic.svc:3100"

        log_format:

          route_id: "$route_id"

          client_ip: "$remote_addr"

          "@timestamp": "$time_iso8601"
```

更新 `loki-logger-ic.yaml`，为 `ApisixRoute` 添加路由级 `log_format`：

loki-logger-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: loki-logger-route

spec:

  ingressClassName: apisix

  http:

    - name: loki-logger-route

      match:

        paths:

          - /anything

        methods:

          - GET

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: loki-logger

          config:

            endpoint_addrs:

              - "http://loki.aic.svc:3100"

            log_format:

              route_id: "$route_id"

              client_ip: "$remote_addr"

              "@timestamp": "$time_iso8601"
```

应用更新后的配置：

```
kubectl apply -f loki-logger-ic.yaml
```

向该路由发送请求以生成新的日志条目：

```
curl -i "http://127.0.0.1:9080/anything"
```

你应该会收到 `HTTP/1.1 200 OK` 响应。

返回 [Grafana Explore 页面](http://localhost:3000/explore)，并重新运行 LogQL 查询 `{job="apisix"}`。新条目会使用路由上配置的格式：

```
{

  "client_ip":"192.168.155.1",

  "route_id":"loki-logger-route",

  "@timestamp":"2026-09-16T12:16:39+00:00"

}
```

### 按条件记录请求体[​](#按条件记录请求体 "按条件记录请求体的直接链接")

以下示例在默认日志格式中按条件记录请求体。下面的路由配置会移除路由级自定义格式。继续操作前，请先移除共享插件元数据：

* Admin API
* ADC
* Ingress Controller

删除 `loki-logger` 插件元数据：

```
curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/loki-logger" -X DELETE \

  -H "X-API-KEY: ${ADMIN_API_KEY}"
```

导出完整的插件元数据集合：

```
adc dump -o adc-metadata.yaml --with-id \

  --include-resource-type plugin_metadata
```

从 `adc-metadata.yaml` 中移除 `loki-logger` 条目，同时保留所有其他插件元数据条目。预览完整集合，确认不包含无关变更：

```
adc diff -f adc-metadata.yaml \

  --include-resource-type plugin_metadata
```

同步已审查的集合：

```
adc sync -f adc-metadata.yaml \

  --include-resource-type plugin_metadata
```

从完整的 `GatewayProxy` 清单中的 `spec.pluginMetadata` 移除 `loki-logger` 条目。保留其他所有元数据条目和现有的 `provider` 配置，然后通过该部署的常规 Kubernetes 或 GitOps 工作流应用更新后的清单。

创建一条启用 `loki-logger` 插件的路由：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes/loki-logger-route" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -H "Content-Type: application/json" \

  -d '{

    "uri": "/anything",

    "plugins": {

      "loki-logger": {

        "endpoint_addrs": ["http://loki:3100"],

        "include_req_body": true,

        "include_req_body_expr": [["arg_log_body", "==", "yes"]]

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - uris:

          - /anything

        name: loki-logger-route

        plugins:

          loki-logger:

            endpoint_addrs:

              - "http://loki:3100"

            include_req_body: true

            include_req_body_expr:

              - - "arg_log_body"

                - "=="

                - "yes"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

ADC 会将标签选择器应用于本地服务，并仅协调带有相同标签的远端服务。预览本示例的变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=loki-logger
```

同步已审查的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=loki-logger
```

* Gateway API
* APISIX CRD

loki-logger-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: loki-logger-plugin-config

spec:

  plugins:

    - name: loki-logger

      config:

        endpoint_addrs:

          - "http://loki.aic.svc:3100"

        include_req_body: true

        include_req_body_expr:

          - - "arg_log_body"

            - "=="

            - "yes"

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: loki-logger-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: loki-logger-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

loki-logger-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: loki-logger-route

spec:

  ingressClassName: apisix

  http:

    - name: loki-logger-route

      match:

        paths:

          - /anything

        methods:

          - GET

          - POST

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: loki-logger

          config:

            endpoint_addrs:

              - "http://loki.aic.svc:3100"

            include_req_body: true

            include_req_body_expr:

              - - "arg_log_body"

                - "=="

                - "yes"
```

应用配置：

```
kubectl apply -f loki-logger-ic.yaml
```

❶ `include_req_body`：设置为 `true` 以记录请求体。

❷ `include_req_body_expr`：仅当 URL 查询字符串 `log_body` 为 `yes` 时，才将请求体添加到默认日志的 `request.body` 字段。

该条件不是自定义格式的数据脱敏边界。引用 `$request_body` 的自定义字段仍可能包含已由 NGINX 缓冲的请求体。详情请参阅[配置参考](https://docs.apiseven.com/hub/loki-logger/configuration.md)。

向该路由发送一个携带满足条件的 URL 查询字符串的请求：

```
curl -i "http://127.0.0.1:9080/anything?log_body=yes" -X POST -d '{"env": "dev"}'
```

打开 [Grafana Explore 页面](http://localhost:3000/explore)，并运行 LogQL 查询 `{job="apisix"}`。匹配的日志条目会包含请求体：

```
{

  "route_id": "loki-logger-route",

  "request": {

    "body": "{\"env\": \"dev\"}",

    "size": 182,

    "method": "POST",

    "url": "http://127.0.0.1:9080/anything?log_body=yes",

    "querystring": {

      "log_body": "yes"

    },

    "uri": "/anything?log_body=yes"

  }

}
```

向该路由发送一个不带 URL 查询字符串的请求：

```
curl -i "http://127.0.0.1:9080/anything" -X POST -d '{"env": "dev"}'
```

重新运行 LogQL 查询 `{job="apisix"}`。新的日志条目不会包含请求体：

```
{

  "route_id": "loki-logger-route",

  "request": {

    "size": 169,

    "method": "POST",

    "url": "http://127.0.0.1:9080/anything",

    "querystring": {},

    "uri": "/anything"

  }

}
```

信息

自定义日志格式不会自动添加已收集的请求体或响应体。请在格式中包含相应变量：

```
{

  "include_req_body": true,

  "include_resp_body": true,

  "log_format": {

    "request_body": "$request_body",

    "response_body": "$resp_body"

  }

}
```

请求体和响应体的大小限制仍然适用。使用 `log_format_extra` 可在不替换默认日志条目的情况下添加自定义字段。
