# File Logger

The `file-logger` plugin writes gateway request and response logs as newline-delimited JSON files for local collection and troubleshooting. It supports detailed default records, focused custom formats, and conditional logging.

Log files are local to each gateway instance. Mount writable persistent storage when logs must survive container or pod replacement.

## Examples[​](#examples "Direct link to Examples")

The examples show how to write a default access record and how to log selected requests with a focused custom format.

For Docker verification, set `GATEWAY_CONTAINER` to the running APISIX or API7 Gateway container. The Kubernetes inspection tabs use `kubectl` instead.

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

### Write a Default Access Log[​](#write-a-default-access-log "Direct link to Write a Default Access Log")

Configure a route to append its access records to a local file:

* 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

      }

    }

  }'
```

Configure ADC to connect to the target backend. The remaining ADC commands read the connection settings from these environment variables:

* 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}"
```

Create the service and route:

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
```

Preview the changes and confirm that they only affect resources for this example:

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

Review `diff.yaml`, then synchronize the labeled service:

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

[Set up the Ingress Controller and gateway](https://docs.api7.ai/ingress-controller/set-up-ingress-controller-and-gateway.md) in the `aic` namespace before continuing. The example path under `/tmp` is ephemeral; mount persistent writable storage on every gateway pod for retained logs.

File logs are instance-local. Run this example with one gateway replica, then set `GATEWAY_POD` to that pod. For API7 Gateway, use the generated gateway pod name from your deployment.

```
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
```

Apply the configuration:

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

Send a request with a query parameter:

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

  --silent \

  --show-error \

  --fail \

  --output /dev/null
```

Read the most recent entry and select stable fields from the default format:

* 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

  }'
```

The entry contains the request and response details:

```
{

  "method": "GET",

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

  "status": 200

}
```

### Log Selected Requests in a Custom Format[​](#log-selected-requests-in-a-custom-format "Direct link to Log Selected Requests in a Custom Format")

Update the route to replace the default entry with selected fields and write a log only when the `log` query parameter equals `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"]

      ]

    ]

  }'
```

In `adc.yaml`, replace the plugin configuration on the existing route:

adc.yaml (route plugin)

```
plugins:

  file-logger:

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

    log_format:

      method: $request_method

      uri: $request_uri

      status: $status

    match:

      - - - arg_log

          - ==

          - 'yes'
```

Preview the updated file:

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

Review `diff.yaml`, then synchronize the labeled service:

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

Update the existing plugin configuration with the Kubernetes API used by the deployment:

* 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'
```

Apply the updated plugin configuration:

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

Clear the example file:

* 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'
```

Send one request that does not match and one that does:

```
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
```

Count the entries and inspect the logged request:

* 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}'
```

Only the matching request is logged in the custom format:

```
Log entries: 1

{

  "method": "GET",

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

  "status": 200

}
```

## Protect and Rotate Log Files[​](#protect-and-rotate-log-files "Direct link to Protect and Rotate Log Files")

The configured parent directory must exist and be writable by the gateway process. A write failure is recorded in the gateway error log and does not fail the proxied request.

Default records contain request, response, upstream, latency, route, service, consumer, client, and gateway details. Headers and query parameters can contain credentials, cookies, and API keys. Restrict access to log files and volumes, and use a focused custom format or masking when sensitive values should not be stored.

The gateway caches open file handles. After rename-based rotation, send the gateway's NGINX log-reopen signal (`USR1`) so it closes the renamed file and opens the configured path. Truncating a file in place keeps the same handle, and subsequent entries continue in the truncated file without a reopen signal.
