# File Logger

`file-logger` 插件将网关请求和响应日志写入以换行符分隔的 JSON 文件，便于本地采集和故障排查。它支持包含详细信息的默认记录、按需选取字段的自定义格式，以及按条件记录日志。

日志文件保存在各个网关实例本地。如果需要在容器或 Pod 替换后保留日志，请挂载可写的持久化存储。

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

以下示例展示如何写入默认访问日志，以及如何使用自定义格式记录指定请求。

通过 Docker 验证时，请将 `GATEWAY_CONTAINER` 设为正在运行的 APISIX 或 API7 网关容器名称。Kubernetes 检查标签页使用 `kubectl`。

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

### 写入默认访问日志[​](#write-a-default-access-log "写入默认访问日志的直接链接")

配置一条路由，将其访问记录追加到本地文件：

* Admin API
* ADC
* Ingress Controller

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

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

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

  -d '{

    "uri": "/anything/file-logger",

    "plugins": {

      "file-logger": {

        "path": "/tmp/file-logger-example.log"

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

配置 ADC，使其连接到目标后端。后续 ADC 命令会从以下环境变量读取连接设置：

* APISIX
* API7 Gateway

```
export ADC_BACKEND=apisix

export ADC_SERVER="http://127.0.0.1:9180"

export ADC_TOKEN="${ADMIN_API_KEY}"
```

```
export ADC_BACKEND=api7ee

export ADC_SERVER="https://{DASHBOARD_ADDR}"

export ADC_TOKEN="{DASHBOARD_TOKEN}"

export ADC_GATEWAY_GROUP="{GATEWAY_GROUP}"
```

创建服务和路由：

adc.yaml

```
services:

  - name: file-logger-service

    labels:

      docs-example: file-logger

    routes:

      - name: file-logger-route

        uris:

          - /anything/file-logger

        plugins:

          file-logger:

            path: /tmp/file-logger-example.log

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，确认其仅影响本示例的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

检查 `diff.yaml`，然后同步带有指定标签的服务：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

继续操作前，请在 `aic` 命名空间中[设置 Ingress Controller 和网关](https://docs.apiseven.com/ingress-controller/set-up-ingress-controller-and-gateway.md)。示例使用的 `/tmp` 路径是临时存储；如需保留日志，请为每个网关 Pod 挂载可写的持久化存储。

文件日志保存在实例本地。运行本示例时，请使用一个网关副本，并将 `GATEWAY_POD` 设为该 Pod 的名称。对于 API7 网关，请使用部署时生成的网关 Pod 名称。

```
kubectl get pods -n aic

export GATEWAY_POD=replace-with-gateway-pod-name
```

* Gateway API
* APISIX CRD

file-logger-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: file-logger-route

spec:

  plugins:

    - name: file-logger

      config:

        path: /tmp/file-logger-example.log

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: file-logger-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything/file-logger

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: file-logger-route

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

file-logger-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v2

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: file-logger-route

spec:

  ingressClassName: apisix

  plugins:

    - name: file-logger

      enable: true

      config:

        path: /tmp/file-logger-example.log

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: file-logger-route

spec:

  ingressClassName: apisix

  http:

    - name: file-logger-route

      match:

        paths:

          - /anything/file-logger

      backends:

        - serviceName: httpbin-external-domain

          servicePort: 80

      plugin_config_name: file-logger-route
```

应用配置：

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

发送包含查询参数的请求：

```
curl "http://127.0.0.1:9080/anything/file-logger?source=docs" \

  --silent \

  --show-error \

  --fail \

  --output /dev/null
```

读取最新的一条记录，并从默认格式中选取稳定的字段：

* Docker
* Kubernetes

```
docker exec "$GATEWAY_CONTAINER" \

  sh -lc 'tail -n 1 /tmp/file-logger-example.log' | \

  jq '{

    method: .request.method,

    uri: .request.uri,

    status: .response.status

  }'
```

```
kubectl exec -n aic "$GATEWAY_POD" -- \

  sh -lc 'tail -n 1 /tmp/file-logger-example.log' | \

  jq '{

    method: .request.method,

    uri: .request.uri,

    status: .response.status

  }'
```

该记录包含请求和响应的详细信息：

```
{

  "method": "GET",

  "uri": "/anything/file-logger?source=docs",

  "status": 200

}
```

### 按自定义格式记录指定请求[​](#log-selected-requests-in-a-custom-format "按自定义格式记录指定请求的直接链接")

更新路由，以指定字段替换默认记录，并仅在 `log` 查询参数等于 `yes` 时写入日志：

* Admin API
* ADC
* Ingress Controller

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

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

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

  -d '{

    "path": "/tmp/file-logger-example.log",

    "log_format": {

      "method": "$request_method",

      "uri": "$request_uri",

      "status": "$status"

    },

    "match": [

      [

        ["arg_log", "==", "yes"]

      ]

    ]

  }'
```

在 `adc.yaml` 中，替换现有路由上的插件配置：

adc.yaml（路由插件）

```
plugins:

  file-logger:

    path: /tmp/file-logger-example.log

    log_format:

      method: $request_method

      uri: $request_uri

      status: $status

    match:

      - - - arg_log

          - ==

          - 'yes'
```

预览更新后的文件：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

检查 `diff.yaml`，然后同步带有指定标签的服务：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

使用当前部署所采用的 Kubernetes API 更新现有插件配置：

* Gateway API
* APISIX CRD

file-logger-ic.yaml

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

kind: PluginConfig

metadata:

  namespace: aic

  name: file-logger-route

spec:

  plugins:

    - name: file-logger

      config:

        path: /tmp/file-logger-example.log

        log_format:

          method: $request_method

          uri: $request_uri

          status: $status

        match:

          - - - arg_log

              - ==

              - 'yes'
```

file-logger-ic.yaml

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

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: file-logger-route

spec:

  ingressClassName: apisix

  plugins:

    - name: file-logger

      enable: true

      config:

        path: /tmp/file-logger-example.log

        log_format:

          method: $request_method

          uri: $request_uri

          status: $status

        match:

          - - - arg_log

              - ==

              - 'yes'
```

应用更新后的插件配置：

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

清空示例日志文件：

* Docker
* Kubernetes

```
docker exec "$GATEWAY_CONTAINER" \

  sh -lc ': > /tmp/file-logger-example.log'
```

```
kubectl exec -n aic "$GATEWAY_POD" -- \

  sh -lc ': > /tmp/file-logger-example.log'
```

分别发送一个不匹配条件的请求和一个匹配条件的请求：

```
curl "http://127.0.0.1:9080/anything/file-logger?log=no" \

  --silent \

  --show-error \

  --fail \

  --output /dev/null



curl "http://127.0.0.1:9080/anything/file-logger?log=yes" \

  --silent \

  --show-error \

  --fail \

  --output /dev/null
```

统计日志条数，并检查记录的请求：

* Docker
* Kubernetes

```
docker exec "$GATEWAY_CONTAINER" \

  sh -lc 'printf "Log entries: "; wc -l < /tmp/file-logger-example.log'



docker exec "$GATEWAY_CONTAINER" \

  sh -lc 'tail -n 1 /tmp/file-logger-example.log' | \

  jq '{method, uri, status}'
```

```
kubectl exec -n aic "$GATEWAY_POD" -- \

  sh -lc 'printf "Log entries: "; wc -l < /tmp/file-logger-example.log'



kubectl exec -n aic "$GATEWAY_POD" -- \

  sh -lc 'tail -n 1 /tmp/file-logger-example.log' | \

  jq '{method, uri, status}'
```

只有匹配条件的请求会按自定义格式记录：

```
Log entries: 1

{

  "method": "GET",

  "uri": "/anything/file-logger?log=yes",

  "status": 200

}
```

## 保护和轮转日志文件[​](#protect-and-rotate-log-files "保护和轮转日志文件的直接链接")

配置路径的父目录必须存在，且网关进程必须对其具有写权限。写入失败会记录在网关错误日志中，不会导致代理请求失败。

默认记录包含请求、响应、上游、延迟、路由、服务、消费者、客户端和网关的详细信息。请求头和查询参数可能包含凭据、Cookie 和 API Key。请限制对日志文件及存储卷的访问；如果不应存储敏感值，请使用仅包含所需字段的自定义格式或进行脱敏。

网关会缓存已打开的文件句柄。通过重命名轮转日志后，请向网关的 NGINX 发送重新打开日志的信号（`USR1`），使其关闭已重命名的文件，并打开配置路径对应的文件。原位截断文件会保留同一个句柄，后续记录会继续写入被截断的文件，无需发送重新打开日志的信号。
