# Google Cloud Logging

`google-cloud-logging` 插件将 APISIX 和 API7 网关的请求与响应日志批量发送到 [Google Cloud Logging](https://cloud.google.com/logging)。它支持选择受监控资源和自定义日志格式。

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

以下示例展示如何使用服务账号密钥将网关日志发送到 Google Cloud Logging，以及如何通过插件元数据添加字段。

插件不使用[应用默认凭据](https://cloud.google.com/docs/authentication/application-default-credentials)。它要求在 `auth_config` 中提供服务账号密钥字段，或在 `auth_file` 中提供服务账号密钥文件路径。当存在更安全的认证方式时，Google 建议避免使用用户管理的服务账号密钥。如果组织政策禁止创建密钥，插件当前的配置接口将无法完成认证。

请按以下步骤为示例准备专用服务账号：

1. 在 Google Cloud 中选择用于接收日志的项目。
2. 前往 **IAM 和管理 → 服务账号**，创建或选择专用服务账号。
3. 为服务账号授予 **Logs Writer** 角色（`roles/logging.logWriter`）。
4. 在服务账号的 **密钥** 标签页中选择 **添加密钥 → 创建新密钥**，选择 **JSON**，然后选择 **创建**。

Google 只允许下载密钥文件一次。请将其存储在组织的凭据管理系统中，不要提交到源代码管理，并在不再需要时撤销该密钥。

### 内联配置凭据[​](#内联配置凭据 "内联配置凭据的直接链接")

`auth_config` 字段直接在插件实例上配置服务账号邮箱、项目 ID、私钥和 OAuth Token 端点。只有当部署的密钥交付系统能够注入这些值、且无需把私钥提交到声明式文件时，才使用此选项。

创建一条启用了 `google-cloud-logging` 插件的路由：

* Admin API
* ADC
* Ingress Controller

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

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

  -d '{

    "id": "google-cloud-logging-route",

    "uri": "/anything",

    "plugins": {

      "google-cloud-logging": {

        "auth_config": {

          "client_email": "replace-with-service-account@your-project-id.iam.gserviceaccount.com",

          "project_id": "your-project-id",

          "private_key": "replace-with-private-key",

          "token_uri": "https://oauth2.googleapis.com/token"

        },

        "batch_max_size": 1

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    labels:

      docs-example: google-cloud-logging

    routes:

      - uris:

          - /anything

        name: google-cloud-logging-route

        plugins:

          google-cloud-logging:

            auth_config:

              client_email: "replace-with-service-account@your-project-id.iam.gserviceaccount.com"

              project_id: "your-project-id"

              private_key: |

                -----BEGIN PRIVATE KEY-----

                ...

                -----END PRIVATE KEY-----

              token_uri: "https://oauth2.googleapis.com/token"

            batch_max_size: 1

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览带有示例标签的服务变更：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=google-cloud-logging
```

同步已审查的变更：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=google-cloud-logging
```

* Gateway API
* APISIX CRD

google-cloud-logging-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: google-cloud-logging-plugin-config

spec:

  plugins:

    - name: google-cloud-logging

      config:

        auth_config:

          client_email: "replace-with-service-account@your-project-id.iam.gserviceaccount.com"

          project_id: "your-project-id"

          private_key: |

            -----BEGIN PRIVATE KEY-----

            ...

            -----END PRIVATE KEY-----

          token_uri: "https://oauth2.googleapis.com/token"

        batch_max_size: 1

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: google-cloud-logging-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: google-cloud-logging-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

google-cloud-logging-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: google-cloud-logging-route

spec:

  ingressClassName: apisix

  http:

    - name: google-cloud-logging-route

      match:

        paths:

          - /anything

        methods:

          - GET

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: google-cloud-logging

          config:

            auth_config:

              client_email: "replace-with-service-account@your-project-id.iam.gserviceaccount.com"

              project_id: "your-project-id"

              private_key: |

                -----BEGIN PRIVATE KEY-----

                ...

                -----END PRIVATE KEY-----

              token_uri: "https://oauth2.googleapis.com/token"

            batch_max_size: 1
```

应用配置：

```
kubectl apply -f google-cloud-logging-ic.yaml
```

为便于验证，该示例会立即发送每条日志。

❶ 配置专用服务账号的邮箱。

❷ 配置用于接收日志的 Google Cloud 项目 ID。

❸ 按下载的 JSON 文件原样配置私钥。在 JSON 负载中保留转义后的换行符。

❹ 保留下载文件中的 Google OAuth Token 端点。示例中的值是 Schema 默认值。

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

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

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

在 Google Cloud 中打开 **Logging → Logs Explorer**，并查询 `log_id("apisix.apache.org/logs")`。结果应包含与以下内容类似的字段：

```
{

  "httpRequest": {

    "requestMethod": "GET",

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

    "status": 200

  },

  "resource": {

    "type": "global"

  },

  "labels": {

    "source": "apache-apisix-google-cloud-logging"

  },

  "logName": "projects/your-project-id/logs/apisix.apache.org%2Flogs"

}
```

### 从文件加载凭据[​](#从文件加载凭据 "从文件加载凭据的直接链接")

`auth_file` 字段将服务账号密钥保留在网关配置之外，并在运行时让插件指向一个 JSON 文件。插件直接读取该文件，要求文件中包含 `entries_uri`；省略 `scope` 时，插件使用 `cloud-platform` OAuth Scope。

在下载的 JSON 密钥中添加以下顶层字段：

```
{

  "entries_uri": "https://logging.googleapis.com/v2/entries:write"

}
```

将生成的文件挂载到每个网关实例的 `/usr/local/apisix/conf/gcp-logging-auth.json`。将文件访问权限限制为网关进程，并使用部署的密钥管理机制，而不是把密钥写入镜像。

创建一条启用了 `google-cloud-logging` 插件的路由：

* Admin API
* ADC
* Ingress Controller

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

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

  -d '{

    "id": "google-cloud-logging-route",

    "uri": "/anything",

    "plugins": {

      "google-cloud-logging": {

        "auth_file": "/usr/local/apisix/conf/gcp-logging-auth.json",

        "batch_max_size": 1

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    labels:

      docs-example: google-cloud-logging

    routes:

      - uris:

          - /anything

        name: google-cloud-logging-route

        plugins:

          google-cloud-logging:

            auth_file: "/usr/local/apisix/conf/gcp-logging-auth.json"

            batch_max_size: 1

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览带有示例标签的服务变更：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=google-cloud-logging
```

同步已审查的变更：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=google-cloud-logging
```

* Gateway API
* APISIX CRD

google-cloud-logging-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: google-cloud-logging-plugin-config

spec:

  plugins:

    - name: google-cloud-logging

      config:

        auth_file: "/usr/local/apisix/conf/gcp-logging-auth.json"

        batch_max_size: 1

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: google-cloud-logging-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: google-cloud-logging-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

google-cloud-logging-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: google-cloud-logging-route

spec:

  ingressClassName: apisix

  http:

    - name: google-cloud-logging-route

      match:

        paths:

          - /anything

        methods:

          - GET

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: google-cloud-logging

          config:

            auth_file: "/usr/local/apisix/conf/gcp-logging-auth.json"

            batch_max_size: 1
```

应用配置：

```
kubectl apply -f google-cloud-logging-ic.yaml
```

❶ 配置已挂载的服务账号 JSON 密钥路径。每个网关实例中都必须存在相同路径。

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

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

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

在 Google Cloud 中打开 **Logging → Logs Explorer**，并查询 `log_id("apisix.apache.org/logs")`。结果应包含与以下内容类似的字段：

```
{

  "httpRequest": {

    "requestMethod": "GET",

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

    "status": 200

  },

  "resource": {

    "type": "global"

  },

  "labels": {

    "source": "apache-apisix-google-cloud-logging"

  },

  "logName": "projects/your-project-id/logs/apisix.apache.org%2Flogs"

}
```

### 使用插件元数据添加字段[​](#使用插件元数据添加字段 "使用插件元数据添加字段的直接链接")

以下示例使用[插件元数据](https://docs.apiseven.com/apisix/key-concepts/plugin-metadata.md)，为每个 `google-cloud-logging` 实例添加选定的请求和响应字段。元数据值引用[内置变量](https://docs.apiseven.com/apisix/reference/built-in-variables.md)，因此同一份配置可应用于多条路由和多个服务。

使用上一个示例中已挂载的凭据文件创建路由：

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

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

  -d '{

    "id": "google-cloud-logging-route",

    "uri": "/anything",

    "plugins": {

      "google-cloud-logging": {

        "auth_file": "/usr/local/apisix/conf/gcp-logging-auth.json",

        "batch_max_size": 1

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

接下来，为 `google-cloud-logging` 配置插件元数据：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/google-cloud-logging" -X PUT \

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

  -d '{

    "log_format_extra": {

      "env": "$http_env",

      "resp_content_type": "$sent_http_Content_Type"

    }

  }'
```

插件元数据是全局集合，无法使用标签选择器隔离。在更改此条目前，请导出完整集合：

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

  --include-resource-type plugin_metadata
```

添加或更新 `google-cloud-logging` 条目，同时保留 `adc-metadata.yaml` 中的所有其他条目：

adc-metadata.yaml (plugin\_metadata excerpt)

```
plugin_metadata:

  # 保留导出文件中的所有其他插件元数据条目。

  google-cloud-logging:

    log_format_extra:

      env: "$http_env"

      resp_content_type: "$sent_http_Content_Type"
```

预览完整的元数据变更，并确认其中没有意外更新或删除：

```
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` 下添加以下条目：

```
google-cloud-logging:

  log_format_extra:

    env: "$http_env"

    resp_content_type: "$sent_http_Content_Type"
```

通过部署的常规 Kubernetes 或 GitOps 工作流应用更新后的完整清单。

❶ 将自定义请求头 `env` 添加到每个默认日志条目。

❷ 将上游响应头 `Content-Type` 添加到每个默认日志条目。

发送带有 `env` 请求头的请求：

```
curl -i "http://127.0.0.1:9080/anything" -H "env: dev"
```

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

在 Google Cloud 中打开 **Logging → Logs Explorer**，并查询 `log_id("apisix.apache.org/logs")`。结果的 `jsonPayload` 应包含与以下内容类似的字段：

```
{

  "env": "dev",

  "resp_content_type": "application/json"

}
```
