This is an automated email from the ASF dual-hosted git repository.

traky pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/apisix.git


The following commit(s) were added to refs/heads/master by this push:
     new 5bfb3b8c3 docs: improve `loki-logger` plugin docs (#11921)
5bfb3b8c3 is described below

commit 5bfb3b8c3d1faba5db251eb3bd8563016b836a52
Author: Traky Deng <[email protected]>
AuthorDate: Mon Apr 7 14:10:47 2025 +0800

    docs: improve `loki-logger` plugin docs (#11921)
---
 docs/en/latest/plugins/loki-logger.md | 404 +++++++++++++++++++++++++---------
 docs/zh/latest/plugins/loki-logger.md | 393 ++++++++++++++++++++++++---------
 2 files changed, 586 insertions(+), 211 deletions(-)

diff --git a/docs/en/latest/plugins/loki-logger.md 
b/docs/en/latest/plugins/loki-logger.md
index 69d101782..74121a4cd 100644
--- a/docs/en/latest/plugins/loki-logger.md
+++ b/docs/en/latest/plugins/loki-logger.md
@@ -6,7 +6,7 @@ keywords:
   - Plugin
   - Loki-logger
   - Grafana Loki
-description: This document contains information about the Apache APISIX 
loki-logger Plugin.
+description: The loki-logger Plugin pushes request and response logs in 
batches to Grafana Loki, via the Loki HTTP API /loki/api/v1/push. The Plugin 
also supports the customization of log formats.
 ---
 
 <!--
@@ -28,92 +28,69 @@ description: This document contains information about the 
Apache APISIX loki-log
 #
 -->
 
+<head>
+  <link rel="canonical" href="https://docs.api7.ai/hub/loki-logger"; />
+</head>
+
 ## Description
 
-The `loki-logger` plugin is used to forward logs to [Grafana 
Loki](https://grafana.com/oss/loki/) for analysis and storage.
+The `loki-logger` Plugin pushes request and response logs in batches to 
[Grafana Loki](https://grafana.com/oss/loki/), via the [Loki HTTP 
API](https://grafana.com/docs/loki/latest/reference/loki-http-api/#loki-http-api)
 `/loki/api/v1/push`. The Plugin also supports the customization of log formats.
 
-When the Plugin is enabled, APISIX will serialize the request context 
information to [Log entries in 
JSON](https://grafana.com/docs/loki/latest/api/#push-log-entries-to-loki) and 
submit it to the batch queue. When the maximum batch size is exceeded, the data 
in the queue is pushed to Grafana Loki. See [batch 
processor](../batch-processor.md) for more details.
+When enabled, the Plugin will serialize the request context information to 
[JSON 
objects](https://grafana.com/docs/loki/latest/api/#push-log-entries-to-loki) 
and add them to the queue, before they are pushed to Loki. See [batch 
processor](../batch-processor.md) for more details.
 
 ## Attributes
 
-| Name | Type | Required | Default | Description |
-|---|---|---|---|---|
-| endpoint_addrs | array[string] | True |  | Loki API base URL, format like 
http://127.0.0.1:3100, supports HTTPS and domain names. If multiple endpoints 
are configured, they will be written randomly. |
-| endpoint_uri | string | False | /loki/api/v1/push | If you are using a log 
collection service that is compatible with the Loki Push API, you can use this 
configuration item to customize the API path. |
-| tenant_id | string | False | fake | Loki tenant ID. According to Loki's 
[multi-tenancy 
documentation](https://grafana.com/docs/loki/latest/operations/multi-tenancy/#multi-tenancy),
 its default value is set to the default value `fake` under single-tenancy. |
-| log_labels | object | False | {job = "apisix"} | Loki log label. [APISIX 
variables](../apisix-variable.md) and [Nginx 
variables](http://nginx.org/en/docs/varindex.html) can be used by prefixing the 
string with `$`, both individual and combined, such as `$host` or 
`$remote_addr:$remote_port`. |
-| ssl_verify        | boolean       | False    | true | When set to `true`, 
verifies the SSL certificate. |
-| timeout           | integer       | False    | 3000ms | Timeout for the Loki 
service HTTP call. Range from 1 to 60,000ms.  |
-| keepalive         | boolean       | False    | true | When set to `true`, 
keeps the connection alive for multiple requests. |
-| keepalive_timeout | integer       | False    | 60000ms | Idle time after 
which the connection is closed. Range greater than or equal than 1000ms.  |
-| keepalive_pool    | integer       | False    | 5       | Connection pool 
limit. Range greater than or equal than 1. |
-| log_format | object | False    |          | Log format declared as key value 
pairs in JSON format. Values only support strings. [APISIX 
variables](../apisix-variable.md) and [Nginx 
variables](http://nginx.org/en/docs/varindex.html) can be used by prefixing the 
string with `$`. |
-| include_req_body       | boolean | False    | false | When set to `true` 
includes the request body in the log. If the request body is too big to be kept 
in the memory, it can't be logged due to Nginx's limitations. |
-| include_req_body_expr  | array   | False    |  | Filter for when the 
`include_req_body` attribute is set to `true`. Request body is only logged when 
the expression set here evaluates to `true`. See 
[lua-resty-expr](https://github.com/api7/lua-resty-expr) for more. |
-| include_resp_body      | boolean | False    | false | When set to `true` 
includes the response body in the log. |
-| include_resp_body_expr | array   | False    |  | Filter for when the 
`include_resp_body` attribute is set to `true`. Response body is only logged 
when the expression set here evaluates to `true`. See 
[lua-resty-expr](https://github.com/api7/lua-resty-expr) for more. |
-
-This plugin supports using batch processors to aggregate and process entries 
(logs/data) in a batch. This avoids the need for frequently submitting the 
data. The batch processor submits data every `5` seconds or when the data in 
the queue reaches `1000`. See [Batch 
Processor](../batch-processor.md#configuration) for more information or setting 
your custom configuration.
-
-### Example of default log format
+| Name | Type | Required | Default | Valid values | Description |
+|---|---|---|---|---|---|
+| endpoint_addrs | array[string] | True |  | | Loki API base URLs, such as 
`http://127.0.0.1:3100`. If multiple endpoints are configured, the log will be 
pushed to a randomly determined endpoint from the list. |
+| endpoint_uri | string | False | /loki/api/v1/push | | URI path to the Loki 
ingest endpoint. |
+| tenant_id | string | False | fake | | Loki tenant ID. According to Loki's 
[multi-tenancy 
documentation](https://grafana.com/docs/loki/latest/operations/multi-tenancy/#multi-tenancy),
 the default value is set to `fake` under single-tenancy. |
+| log_labels | object | False | {job = "apisix"} | | Loki log label. Support 
[NGINX variables](https://nginx.org/en/docs/varindex.html) and constant strings 
in values. Variables should be prefixed with a `$` sign. For example, the label 
can be `{"origin" = "apisix"}` or `{"origin" = "$remote_addr"}`. |
+| ssl_verify        | boolean       | False    | true | | If true, verify 
Loki's SSL certificates. |
+| timeout           | integer       | False    | 3000 | [1, 60000] | Timeout 
for the Loki service HTTP call in milliseconds.  |
+| keepalive         | boolean       | False    | true |  | If true, keep the 
connection alive for multiple requests. |
+| keepalive_timeout | integer       | False    | 60000 | >=1000 | Keepalive 
timeout in milliseconds.  |
+| keepalive_pool    | integer       | False    | 5       | >=1 | Maximum 
number of connections in the connection pool.  |
+| log_format | object | False    |          | | Custom log format in key-value 
pairs in JSON format. Support [APISIX variables](../apisix-variable.md) and 
[NGINX variables](http://nginx.org/en/docs/varindex.html) in values. |
+| name | string | False    | loki-logger | | Unique identifier of the Plugin 
for the batch processor. If you use [Prometheus](./prometheus.md) to monitor 
APISIX metrics, the name is exported in `apisix_batch_process_entries`. |
+| include_req_body       | boolean | False    | false | | If true, include the 
request body in the log. Note that if the request body is too big to be kept in 
the memory, it can not be logged due to NGINX's limitations. |
+| include_req_body_expr  | array[array]   | False    |  | | An array of one or 
more conditions in the form of 
[lua-resty-expr](https://github.com/api7/lua-resty-expr). Used when the 
`include_req_body` is true. Request body would only be logged when the 
expressions configured here evaluate to true. |
+| include_resp_body      | boolean | False    | false | | If true, include the 
response body in the log.  |
+| include_resp_body_expr | array[array]   | False    |  | | An array of one or 
more conditions in the form of 
[lua-resty-expr](https://github.com/api7/lua-resty-expr). Used when the 
`include_resp_body` is true. Response body would only be logged when the 
expressions configured here evaluate to true. |
+
+This Plugin supports using batch processors to aggregate and process entries 
(logs/data) in a batch. This avoids the need for frequently submitting the 
data. The batch processor submits data every `5` seconds or when the data in 
the queue reaches `1000`. See [Batch 
Processor](../batch-processor.md#configuration) for more information or setting 
your custom configuration.
+
+## Plugin Metadata
+
+You can also configure log format on a global scale using the [Plugin 
Metadata](../terminology/plugin-metadata.md), which configures the log format 
for all `loki-logger` Plugin instances. If the log format configured on the 
individual Plugin instance differs from the log format configured on Plugin 
metadata, the log format configured on the individual Plugin instance takes 
precedence.
 
-```json
-{
-    "request": {
-        "headers": {
-            "connection": "close",
-            "host": "localhost",
-            "test-header": "only-for-test#1"
-        },
-        "method": "GET",
-        "uri": "/hello",
-        "url": "http://localhost:1984/hello";,
-        "size": 89,
-        "querystring": {}
-    },
-    "client_ip": "127.0.0.1",
-    "start_time": 1704525701293,
-    "apisix_latency": 100.99994659424,
-    "response": {
-        "headers": {
-            "content-type": "text/plain",
-            "server": "APISIX/3.7.0",
-            "content-length": "12",
-            "connection": "close"
-        },
-        "status": 200,
-        "size": 118
-    },
-    "route_id": "1",
-    "loki_log_time": "1704525701293000000",
-    "upstream_latency": 5,
-    "latency": 105.99994659424,
-    "upstream": "127.0.0.1:1980",
-    "server": {
-        "hostname": "localhost",
-        "version": "3.7.0"
-    },
-    "service_id": ""
-}
-```
+| Name | Type | Required | Default | Description |
+|------|------|----------|---------|-------------|
+| log_format | object | False |  | Custom log format in key-value pairs in 
JSON format. Support [APISIX variables](../apisix-variable.md) and [NGINX 
variables](http://nginx.org/en/docs/varindex.html) in values. |
 
-## Metadata
+## Examples
 
-You can also set the format of the logs by configuring the Plugin metadata. 
The following configurations are available:
+The examples below demonstrate how you can configure `loki-logger` Plugin for 
different scenarios.
 
-| Name | Type | Required | Default | Description |
-|------|------|----------|---------|-------------|
-| log_format | object | False |  | Log format declared as key value pairs in 
JSON format. Values only support strings. [APISIX 
variables](../apisix-variable.md) and [Nginx 
variables](http://nginx.org/en/docs/varindex.html) can be used by prefixing the 
string with `$`. |
+To follow along the examples, start a sample Loki instance in Docker:
 
-:::info IMPORTANT
+```shell
+wget 
https://raw.githubusercontent.com/grafana/loki/v3.0.0/cmd/loki/loki-local-config.yaml
 -O loki-config.yaml
+docker run --name loki -d -v $(pwd):/mnt/config -p 3100:3100 
grafana/loki:3.2.1 -config.file=/mnt/config/loki-config.yaml
+```
 
-Configuring the plugin metadata is global in scope. This means that it will 
take effect on all Routes and Services which use the `loki-logger` plugin.
+Additionally, start a Grafana instance to view and visualize the logs:
 
-:::
+```shell
+docker run -d --name=apisix-quickstart-grafana \
+  -p 3000:3000 \
+  grafana/grafana-oss
+```
 
-The example below shows how you can configure through the Admin API:
+To connect Loki and Grafana, visit Grafana at 
[`http://localhost:3000`](http://localhost:3000). Under __Connections > Data 
sources__, add a new data source and select Loki. Your connection URL should 
follow the format of `http://{your_ip_address}:3100`. When saving the new data 
source, Grafana should also test the connection, and you are expected to see 
Grafana notifying the data source is successfully connected.
 
 :::note
+
 You can fetch the `admin_key` from `config.yaml` and save to an environment 
variable with the following command:
 
 ```bash
@@ -122,73 +99,282 @@ admin_key=$(yq '.deployment.admin.admin_key[0].key' 
conf/config.yaml | sed 's/"/
 
 :::
 
+### Log Requests and Responses in Default Log Format
+
+The following example demonstrates how you can configure the `loki-logger` 
Plugin on a Route to log requests and responses going through the route.
+
+Create a Route with the `loki-logger` Plugin and configure the address of Loki:
+
 ```shell
-curl http://127.0.0.1:9180/apisix/admin/plugin_metadata/loki-logger -H 
"X-API-KEY: $admin_key" -X PUT -d '
-{
-    "log_format": {
-        "host": "$host",
-        "@timestamp": "$time_iso8601",
-        "client_ip": "$remote_addr"
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "loki-logger-route",
+    "uri": "/anything",
+    "plugins": {
+      "loki-logger": {
+        "endpoint_addrs": ["http://192.168.1.5:3100";]
+      }
+    },
+    "upstream": {
+      "nodes": {
+        "httpbin.org:80": 1
+      },
+      "type": "roundrobin"
     }
-}'
+  }'
 ```
 
-With this configuration, your logs would be formatted as shown below:
+Send a few requests to the Route to generate log entries:
 
 ```shell
-{"host":"localhost","@timestamp":"2020-09-23T19:05:05-04:00","client_ip":"127.0.0.1","route_id":"1"}
-{"host":"localhost","@timestamp":"2020-09-23T19:05:05-04:00","client_ip":"127.0.0.1","route_id":"1"}
+curl "http://127.0.0.1:9080/anything";
 ```
 
-## Enable plugin
+You should receive `HTTP/1.1 200 OK` responses for all requests.
 
-The example below shows how you can enable the `loki-logger` plugin on a 
specific Route:
+Navigate to the [Grafana explore view](http://localhost:3000/explore) and run 
a query `job = apisix`. You should see a number of logs corresponding to your 
requests, such as the following:
 
-```shell
-curl http://127.0.0.1:9180/apisix/admin/routes/1 -H "X-API-KEY: $admin_key" -X 
PUT -d '
+```json
 {
+  "route_id": "loki-logger-route",
+  "response": {
+    "status": 200,
+    "headers": {
+      "date": "Fri, 03 Jan 2025 03:54:26 GMT",
+      "server": "APISIX/3.11.0",
+      "access-control-allow-credentials": "true",
+      "content-length": "391",
+      "access-control-allow-origin": "*",
+      "content-type": "application/json",
+      "connection": "close"
+    },
+    "size": 619
+  },
+  "start_time": 1735876466,
+  "client_ip": "192.168.65.1",
+  "service_id": "",
+  "apisix_latency": 5.0000038146973,
+  "upstream": "34.197.122.172:80",
+  "upstream_latency": 666,
+  "server": {
+    "hostname": "0b9a772e68f8",
+    "version": "3.11.0"
+  },
+  "request": {
+    "headers": {
+      "user-agent": "curl/8.6.0",
+      "accept": "*/*",
+      "host": "127.0.0.1:9080"
+    },
+    "size": 85,
+    "method": "GET",
+    "url": "http://127.0.0.1:9080/anything";,
+    "querystring": {},
+    "uri": "/anything"
+  },
+  "latency": 671.0000038147
+}
+```
+
+This verifies that Loki has been receiving logs from APISIX. You may also 
create dashboards in Grafana to further visualize and analyze the logs.
+
+### Customize Log Format with Plugin Metadata
+
+The following example demonstrates how you can customize log format using 
[Plugin Metadata](../terminology/plugin-metadata.md).
+
+Create a Route with the `loki-logger` plugin:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "loki-logger-route",
+    "uri": "/anything",
     "plugins": {
-        "loki-logger": {
-            "endpoint_addrs" : ["http://127.0.0.1:3100";]
-        }
+      "loki-logger": {
+        "endpoint_addrs": ["http://192.168.1.5:3100";]
+      }
     },
     "upstream": {
-       "nodes": {
-           "127.0.0.1:1980": 1
-       },
-       "type": "roundrobin"
-    },
-    "uri": "/hello"
-}'
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org": 1
+      }
+    }
+  }'
 ```
 
-## Example usage
+Configure Plugin metadata for `loki-logger`, which will update the log format 
for all routes of which requests would be logged:
 
-Now, if you make a request to APISIX, it will be logged in your Loki server:
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/loki-logger"; -X PUT \
+  -H 'X-API-KEY: ${admin_key}' \
+  -d '{
+    "log_format": {
+      "host": "$host",
+      "client_ip": "$remote_addr",
+      "route_id": "$route_id",
+      "@timestamp": "$time_iso8601"
+    }
+  }'
+```
+
+Send a request to the Route to generate a new log entry:
 
 ```shell
-curl -i http://127.0.0.1:9080/hello
+curl -i "http://127.0.0.1:9080/anything";
+```
+
+You should receive an `HTTP/1.1 200 OK` response.
+
+Navigate to the [Grafana explore view](http://localhost:3000/explore) and run 
a query `job = apisix`. You should see a log entry corresponding to your 
request, similar to the following:
+
+```json
+{
+  "@timestamp":"2025-01-03T21:11:34+00:00",
+  "client_ip":"192.168.65.1",
+  "route_id":"loki-logger-route",
+  "host":"127.0.0.1"
+}
 ```
 
-## Delete the plugin
+If the Plugin on a Route specifies a specific log format, it will take 
precedence over the log format specified in the Plugin metadata. For instance, 
update the Plugin on the previous Route as such:
 
-When you need to remove the `loki-logger` plugin, you can delete the 
corresponding JSON configuration with the following command and APISIX will 
automatically reload the relevant configuration without restarting the service:
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes/loki-logger-route"; -X PATCH \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "plugins": {
+      "loki-logger": {
+        "log_format": {
+          "route_id": "$route_id",
+          "client_ip": "$remote_addr",
+          "@timestamp": "$time_iso8601"
+        }
+      }
+    }
+  }'
+```
+
+Send a request to the Route to generate a new log entry:
 
 ```shell
-curl http://127.0.0.1:9180/apisix/admin/routes/1  -H "X-API-KEY: $admin_key" 
-X PUT -d '
+curl -i "http://127.0.0.1:9080/anything";
+```
+
+You should receive an `HTTP/1.1 200 OK` response.
+
+Navigate to the [Grafana explore view](http://localhost:3000/explore) and 
re-run the query `job = apisix`. You should see a log entry corresponding to 
your request, consistent with the format configured on the route, similar to 
the following:
+
+```json
 {
-    "methods": ["GET"],
-    "uri": "/hello",
-    "plugins": {},
+  "client_ip":"192.168.65.1",
+  "route_id":"loki-logger-route",
+  "@timestamp":"2025-01-03T21:19:45+00:00"
+}
+```
+
+### Log Request Bodies Conditionally
+
+The following example demonstrates how you can conditionally log request body.
+
+Create a Route with `loki-logger` to only log request body if the URL query 
string `log_body` is `yes`:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "loki-logger-route",
+    "uri": "/anything",
+    "plugins": {
+      "loki-logger": {
+        "endpoint_addrs": ["http://192.168.1.5:3100";],
+        "include_req_body": true,
+        "include_req_body_expr": [["arg_log_body", "==", "yes"]]
+      }
+    },
     "upstream": {
-        "type": "roundrobin",
-        "nodes": {
-            "127.0.0.1:1980": 1
-        }
+      "nodes": {
+        "httpbin.org:80": 1
+      },
+      "type": "roundrobin"
     }
-}'
+  }'
+```
+
+Send a request to the Route with a URL query string satisfying the condition:
+
+```shell
+curl -i "http://127.0.0.1:9080/anything?log_body=yes"; -X POST -d '{"env": 
"dev"}'
+```
+
+Navigate to the [Grafana explore view](http://localhost:3000/explore) and run 
the query `job = apisix`. You should see a log entry corresponding to your 
request, where the request body is logged:
+
+```json
+{
+  "route_id": "loki-logger-route",
+  ...,
+  "request": {
+    "headers": {
+      ...
+    },
+    "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"
+  },
+  "latency": 809.99994277954
+}
+```
+
+Send a request to the Route without any URL query string:
+
+```shell
+curl -i "http://127.0.0.1:9080/anything"; -X POST -d '{"env": "dev"}'
 ```
 
+Navigate to the [Grafana explore view](http://localhost:3000/explore) and run 
the query `job = apisix`. You should see a log entry corresponding to your 
request, where the request body is not logged:
+
+```json
+{
+  "route_id": "loki-logger-route",
+  ...,
+  "request": {
+    "headers": {
+      ...
+    },
+    "size": 169,
+    "method": "POST",
+    "url": "http://127.0.0.1:9080/anything";,
+    "querystring": {},
+    "uri": "/anything"
+  },
+  "latency": 557.00016021729
+}
+```
+
+:::info
+
+If you have customized the `log_format` in addition to setting 
`include_req_body` or `include_resp_body` to `true`, the Plugin would not 
include the bodies in the logs.
+
+As a workaround, you may be able to use the NGINX variable `$request_body` in 
the log format, such as:
+
+```json
+{
+  "kafka-logger": {
+    ...,
+    "log_format": {"body": "$request_body"}
+  }
+}
+```
+
+:::
+
 ## FAQ
 
 ### Logs are not pushed properly
diff --git a/docs/zh/latest/plugins/loki-logger.md 
b/docs/zh/latest/plugins/loki-logger.md
index 5e0a5a41e..dc4d41211 100644
--- a/docs/zh/latest/plugins/loki-logger.md
+++ b/docs/zh/latest/plugins/loki-logger.md
@@ -6,7 +6,7 @@ keywords:
   - Plugin
   - Loki-logger
   - Grafana Loki
-description: 本文件包含关于 Apache APISIX loki-logger 插件的信息。
+description: loki-logger 插件通过 Loki HTTP API /loki/api/v1/push 将请求和响应日志批量推送到 
Grafana Loki。该插件还支持自定义日志格式。
 ---
 
 <!--
@@ -28,168 +28,357 @@ description: 本文件包含关于 Apache APISIX loki-logger 插件的信息。
 #
 -->
 
+<head>
+  <link rel="canonical" href="https://docs.api7.ai/hub/loki-logger"; />
+</head>
+
 ## 描述
 
-`loki-logger` 插件用于将日志转发到 [Grafana Loki](https://grafana.com/oss/loki/) 进行分析和存储。
+`loki-logger` 插件通过 [Loki HTTP 
API](https://grafana.com/docs/loki/latest/reference/loki-http-api/#loki-http-api)
 `/loki/api/v1/push` 将请求和响应日志批量推送到 [Grafana 
Loki](https://grafana.com/oss/loki/)。该插件还支持自定义日志格式。
 
-当启用该插件时,APISIX 将把请求上下文信息序列化为 [JSON 
中的日志条目](https://grafana.com/docs/loki/latest/api/#push-log-entries-to-loki) 
并将其提交到批处理队列中。当队列中的数据量超过最大批处理大小时,数据将被推送到 Grafana Loki。有关更多详细信息,请参阅批处理处理器 [batch 
processor](../batch-processor.md)。
+启用后,插件会将请求上下文信息序列化为 [JSON 
object](https://grafana.com/docs/loki/latest/api/#push-log-entries-to-loki) 
并将其添加到队列中,然后再将其推送到 Loki。有关更多详细信息,请参阅批处理处理器 [batch 
processor](../batch-processor.md)。
 
 ## 属性
 
-| 名称 | 类型 | 必选项 | 默认值 | 描述 |
+| 名称 | 类型 | 必选项 | 默认值 | 有效值 | 描述 |
 |--|---|---|---|---|
-| endpoint_addrs | array[string] | True |  | Loki API 基础 URL,格式如 
http://127.0.0.1:3100,支持 HTTPS 和域名。如果配置了多个端点,它们将随机选择一个进行写入 |
-| endpoint_uri | string | False | /loki/api/v1/push | 如果您正在使用与 Loki Push API 
兼容的日志收集服务,您可以使用此配置项自定义 API 路径。 |
-| tenant_id | string | False | fake | Loki 租户 ID。根据 Loki 的 
[多租户文档](https://grafana.com/docs/loki/latest/operations/multi-tenancy/#multi-tenancy),在单租户模式下,默认值设置为
 `fake`。 |
-| log_labels | object | False | {job = "apisix"} | Loki 日志标签。您可以使用 [APISIX 
变量](../apisix-variable.md) 和 [Nginx 变量](http://nginx.org/en/docs/varindex.html) 
只需在字符串前面加上 `$` 符号即可,可以使用单个变量或组合变量,例如 `$host` 或 `$remote_addr:$remote_port`。 |
-| ssl_verify    | boolean       | False    | true | 当设置为 `true` 时,将验证 SSL 证书。 |
-| timeout       | integer       | False    | 3000ms | Loki 服务 HTTP 调用的超时时间,范围从 
1 到 60,000 毫秒。  |
-| keepalive     | boolean       | False    | true | 当设置为 `true` 
时,会保持连接以供多个请求使用。 |
-| keepalive_timeout | integer       | False    | 60000ms | 连接空闲时间后关闭连接。范围大于或等于 
1000 毫秒。  |
-| keepalive_pool | integer       | False    | 5       | 连接池限制。范围大于或等于 1。 |
-| log_format | object | False    |          | 以 JSON 
格式声明的键值对形式的日志格式。值仅支持字符串类型。可以通过在字符串前面加上 `$` 来使用 [APISIX 
变量](../apisix-variable.md) 和 [Nginx 变量](http://nginx.org/en/docs/varindex.html) 
。 |
-| include_req_body   | boolean | False    | false | 当设置为 `true` 
时,日志中将包含请求体。如果请求体太大而无法在内存中保存,则由于 Nginx 的限制,无法记录请求体。|
-| include_req_body_expr | array   | False    |  | 当 `include_req_body` 属性设置为 
`true` 时的过滤器。只有当此处设置的表达式求值为 `true` 时,才会记录请求体。有关更多信息,请参阅 
[lua-resty-expr](https://github.com/api7/lua-resty-expr) 。 |
-| include_resp_body  | boolean | False    | false | 当设置为 `true` 时,日志中将包含响应体。 |
-| include_resp_body_expr | array   | False    | | 当 `include_resp_body` 属性设置为 
`true` 时的过滤器。只有当此处设置的表达式求值为 `true` 时,才会记录响应体。有关更多信息,请参阅 
[lua-resty-expr](https://github.com/api7/lua-resty-expr) 。 |
+| end_addrs | array[string] | 是 | | | Loki API URL,例如 
`http://127.0.0.1:3100`。如果配置了多个端点,日志将被推送到列表中随机确定的端点。 |
+| end_uri | string | 否 | /loki/api/v1/push | | Loki 提取端点的 URI 路径。 |
+| tenant_id | string | 否 | fake | | Loki 租户 ID。根据 Loki 的 
[多租户文档](https://grafana.com/docs/loki/latest/operations/multi-tenancy/#multi-tenancy),在单租户下默认值设置为
 `fake`。 |
+| log_labels | object | 否 | {job = "apisix"} | | Loki 日志标签。支持 [NGINX 
变量](https://nginx.org/en/docs/varindex.html) 和值中的常量字符串。变量应以 `$` 符号为前缀。例如,标签可以是 
`{"origin" = "apisix"}` 或 `{"origin" = "$remote_addr"}`。|
+| ssl_verify | boolean | 否 | true | | 如果为 true,则验证 Loki 的 SSL 证书。|
+| timeout | integer | 否 | 3000 | [1, 60000] | Loki 服务 HTTP 调用的超时时间(以毫秒为单位)。|
+| keepalive | boolean | 否 | true | | 如果为 true,则保持连接以应对多个请求。|
+| keepalive_timeout | integer | 否 | 60000 | >=1000 | Keepalive 超时时间(以毫秒为单位)。|
+| keepalive_pool | integer | 否 | 5 | >=1 | 连接池中的最大连接数。|
+| log_format | object | 否 | | |自定义日志格式为 JSON 格式的键值对。值中支持 [APISIX 
变量](../apisix-variable.md) 和 [NGINX 
变量](http://nginx.org/en/docs/varindex.html)。 |
+| name | string | 否 | loki-logger | | 批处理器插件的唯一标识符。如果使用 
[Prometheus](./prometheus.md) 监控 APISIX 指标,则名称会导出到 
`apisix_batch_process_entries`。 |
+| include_req_body | boolean | 否 | false | | 如果为 
true,则将请求正文包含在日志中。请注意,如果请求正文太大而无法保存在内存中,则由于 NGINX 的限制而无法记录。 |
+| include_req_body_expr | array[array] | 否 | | |一个或多个 
[lua-resty-expr](https://github.com/api7/lua-resty-expr) 形式条件的数组。在 
`include_req_body` 为 true 时使用。仅当此处配置的表达式计算结果为 true 时,才会记录请求正文。|
+| include_resp_body | boolean | 否 | false | | 如果为 true,则将响应正文包含在日志中。|
+| include_resp_body_expr | array[array] | 否 | | | 一个或多个 
[lua-resty-expr](https://github.com/api7/lua-resty-expr) 形式条件的数组。在 
`include_resp_body` 为 true 时使用。仅当此处配置的表达式计算结果为 true 时,才会记录响应正文。|
 
 该插件支持使用批处理器对条目(日志/数据)进行批量聚合和处理,避免了频繁提交数据的需求。批处理器每隔 `5` 秒或当队列中的数据达到 `1000` 
时提交数据。有关更多信息或设置自定义配置,请参阅 [批处理器](../batch-processor.md#configuration)。
 
-### 默认日志格式示例
+## Plugin Metadata
+
+您还可以使用 [Plugin Metadata](../terminology/plugin-metadata.md) 全局配置日志格式,该 Plugin 
Metadata 配置所有 `loki-logger` 插件实例的日志格式。如果在单个插件实例上配置的日志格式与在 Plugin Metadata 
上配置的日志格式不同,则在单个插件实例上配置的日志格式优先。
+
+| 名称 | 类型 | 必选项 | 默认值 | 描述 |
+|------|------|----------|--|-------------|
+| log_format | object | 否 |  | 日志格式以 JSON 格式声明为键值对。值只支持字符串类型。可以通过在字符串前面加上 `$` 
来使用 [APISIX 变量](../apisix-variable.md) 和 [NGINX 
变量](http://nginx.org/en/docs/varindex.html) 。 |
+
+## 示例
+
+下面的示例演示了如何为不同场景配置 `loki-logger` 插件。
+
+为了遵循示例,请在 Docker 中启动一个示例 Loki 实例:
+
+```shell
+wget 
https://raw.githubusercontent.com/grafana/loki/v3.0.0/cmd/loki/loki-local-config.yaml
 -O loki-config.yaml
+docker run --name loki -d -v $(pwd):/mnt/config -p 3100:3100 
grafana/loki:3.2.1 -config.file=/mnt/config/loki-config.yaml
+```
+
+此外,启动 Grafana 实例来查看和可视化日志:
+
+```shell
+docker run -d --name=apisix-quickstart-grafana \
+  -p 3000:3000 \
+  grafana/grafana-oss
+```
+
+要连接 Loki 和 Grafana,请访问 Grafana,网址为 
[`http://localhost:3000`](http://localhost:3000)。在 __Connections > Data 
sources__ 下,添加新数据源并选择 Loki。您的连接 URL 应遵循 `http://{your_ip_address}:3100` 
的格式。保存新数据源时,Grafana 还应测试连接,您应该会看到 Grafana 通知数据源已成功连接。
+
+:::note
+
+您可以这样从 `config.yaml` 中获取 `admin_key` 并存入环境变量:
+
+```bash
+admin_key=$(yq '.deployment.admin.admin_key[0].key' conf/config.yaml | sed 
's/"//g')
+```
+
+:::
+
+### 以默认日志格式记录请求和响应
+
+以下示例演示了如何在路由上配置 `loki-logger` 插件以记录通过路由的请求和响应。
+
+使用 `loki-logger` 插件创建路由并配置 Loki 的地址:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "loki-logger-route",
+    "uri": "/anything",
+    "plugins": {
+      "loki-logger": {
+        "endpoint_addrs": ["http://192.168.1.5:3100";]
+      }
+    },
+    "upstream": {
+      "nodes": {
+        "httpbin.org:80": 1
+      },
+      "type": "roundrobin"
+    }
+  }'
+```
+
+向路由发送一些请求以生成日志条目:
+
+```shell
+curl "http://127.0.0.1:9080/anything";
+```
+
+您应该会收到所有请求的“HTTP/1.1 200 OK”响应。
+
+导航到 [Grafana explore view](http://localhost:3000/explore) 并运行查询 `job = 
apisix`。您应该会看到与您的请求相对应的许多日志,例如以下内容:
 
 ```json
 {
-  "request": {
-    "headers": {
-      "connection": "close",
-      "host": "localhost",
-      "test-header": "only-for-test#1"
-    },
-    "method": "GET",
-    "uri": "/hello",
-    "url": "http://localhost:1984/hello";,
-    "size": 89,
-    "querystring": {}
-  },
-  "client_ip": "127.0.0.1",
-  "start_time": 1704525701293,
-  "apisix_latency": 100.99994659424,
+  "route_id": "loki-logger-route",
   "response": {
+    "status": 200,
     "headers": {
-      "content-type": "text/plain",
-      "server": "APISIX/3.7.0",
-      "content-length": "12",
+      "date": "Fri, 03 Jan 2025 03:54:26 GMT",
+      "server": "APISIX/3.11.0",
+      "access-control-allow-credentials": "true",
+      "content-length": "391",
+      "access-control-allow-origin": "*",
+      "content-type": "application/json",
       "connection": "close"
     },
-    "status": 200,
-    "size": 118
+    "size": 619
   },
-  "route_id": "1",
-  "loki_log_time": "1704525701293000000",
-  "upstream_latency": 5,
-  "latency": 105.99994659424,
-  "upstream": "127.0.0.1:1980",
+  "start_time": 1735876466,
+  "client_ip": "192.168.65.1",
+  "service_id": "",
+  "apisix_latency": 5.0000038146973,
+  "upstream": "34.197.122.172:80",
+  "upstream_latency": 666,
   "server": {
-    "hostname": "localhost",
-    "version": "3.7.0"
+    "hostname": "0b9a772e68f8",
+    "version": "3.11.0"
   },
-  "service_id": ""
+  "request": {
+    "headers": {
+      "user-agent": "curl/8.6.0",
+      "accept": "*/*",
+      "host": "127.0.0.1:9080"
+    },
+    "size": 85,
+    "method": "GET",
+    "url": "http://127.0.0.1:9080/anything";,
+    "querystring": {},
+    "uri": "/anything"
+  },
+  "latency": 671.0000038147
 }
 ```
 
-## 元数据
+这验证了 Loki 已从 APISIX 接收日志。您还可以在 Grafana 中创建仪表板,以进一步可视化和分析日志。
 
-您还可以通过配置插件元数据来设置日志的格式。以下配置项可供选择:
+### 使用 Plugin Metadata 自定义日志格式
 
-| 名称 | 类型 | 必选项 | 默认值 | 描述 |
-|------|------|----------|--|-------------|
-| log_format | object | False |  | 日志格式以 JSON 格式声明为键值对。值只支持字符串类型。可以通过在字符串前面加上 
`$` 来使用 [APISIX 变量](../apisix-variable.md) 和 [Nginx 
变量](http://nginx.org/en/docs/varindex.html) 。 |
+以下示例演示了如何使用 [Plugin Metadata](../terminology/plugin-metadata.md) 自定义日志格式。
 
-:::info 重要提示
+使用 `loki-logger` 插件创建路由:
 
-配置插件元数据具有全局范围。这意味着它将对使用 `loki-logger` 插件的所有路由和服务生效。
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "loki-logger-route",
+    "uri": "/anything",
+    "plugins": {
+      "loki-logger": {
+        "endpoint_addrs": ["http://192.168.1.5:3100";]
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org": 1
+      }
+    }
+  }'
+```
 
-:::
+为 `loki-logger` 配置 Plugin Metadata,它将更新所有需要记录请求的路由的日志格式:
 
-以下示例展示了如何通过 Admin API 进行配置:
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/loki-logger"; -X PUT \
+  -H 'X-API-KEY: ${admin_key}' \
+  -d '{
+    "log_format": {
+      "host": "$host",
+      "client_ip": "$remote_addr",
+      "route_id": "$route_id",
+      "@timestamp": "$time_iso8601"
+    }
+  }'
+```
 
-:::note
+向路由发送请求以生成新的日志条目:
 
-您可以这样从 `config.yaml` 中获取 `admin_key` 并存入环境变量:
+```shell
+curl -i "http://127.0.0.1:9080/anything";
+```
 
-```bash
-admin_key=$(yq '.deployment.admin.admin_key[0].key' conf/config.yaml | sed 
's/"//g')
+您应该会收到 `HTTP/1.1 200 OK` 响应。
+
+导航到 [Grafana explore view](http://localhost:3000/explore) 并运行查询 `job = 
apisix`。您应该会看到与您的请求相对应的日志条目,类似于以下内容:
+
+```json
+{
+  "@timestamp":"2025-01-03T21:11:34+00:00",
+  "client_ip":"192.168.65.1",
+  "route_id":"loki-logger-route",
+  "host":"127.0.0.1"
+}
 ```
 
-:::
+如果路由上的插件指定了特定的日志格式,它将优先于 Plugin Metadata 中指定的日志格式。例如,按如下方式更新上一个路由上的插件:
 
 ```shell
-curl http://127.0.0.1:9180/apisix/admin/plugin_metadata/loki-logger -H 
"X-API-KEY: $admin_key" -X PUT -d '
-{
-    "log_format": {
-        "host": "$host",
-        "@timestamp": "$time_iso8601",
-        "client_ip": "$remote_addr"
+curl "http://127.0.0.1:9180/apisix/admin/routes/loki-logger-route"; -X PATCH \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "plugins": {
+      "loki-logger": {
+        "log_format": {
+          "route_id": "$route_id",
+          "client_ip": "$remote_addr",
+          "@timestamp": "$time_iso8601"
+        }
+      }
     }
-}'
+  }'
 ```
 
-使用这个配置,您的日志将被格式化为以下形式:
+向路由发送请求以生成新的日志条目:
 
 ```shell
-{"host":"localhost","@timestamp":"2020-09-23T19:05:05-04:00","client_ip":"127.0.0.1","route_id":"1"}
-{"host":"localhost","@timestamp":"2020-09-23T19:05:05-04:00","client_ip":"127.0.0.1","route_id":"1"}
+curl -i "http://127.0.0.1:9080/anything";
 ```
 
-## 启用插件
+您应该会收到 `HTTP/1.1 200 OK` 响应。
 
-以下示例展示了如何在特定的路由上启用 `loki-logger` 插件:
+导航到 [Grafana explore view](http://localhost:3000/explore) 并重新运行查询 `job = 
apisix`。您应该会看到与您的请求相对应的日志条目,与路由上配置的格式一致,类似于以下内容:
 
-```shell
-curl http://127.0.0.1:9180/apisix/admin/routes/1 -H "X-API-KEY: $admin_key" -X 
PUT -d '
+```json
 {
+  "client_ip":"192.168.65.1",
+  "route_id":"loki-logger-route",
+  "@timestamp":"2025-01-03T21:19:45+00:00"
+}
+```
+
+### 有条件地记录请求主体
+
+以下示例演示了如何有条件地记录请求主体。
+
+使用 `loki-logger` 创建路由,仅在 URL 查询字符串 `log_body` 为 `yes` 时记录请求主体:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "loki-logger-route",
+    "uri": "/anything",
     "plugins": {
-        "loki-logger": {
-            "endpoint_addrs" : ["http://127.0.0.1:3100";]
-        }
+      "loki-logger": {
+        "endpoint_addrs": ["http://192.168.1.5:3100";],
+        "include_req_body": true,
+        "include_req_body_expr": [["arg_log_body", "==", "yes"]]
+      }
     },
     "upstream": {
-       "nodes": {
-           "127.0.0.1:1980": 1
-       },
-       "type": "roundrobin"
-    },
-    "uri": "/hello"
-}'
+      "nodes": {
+        "httpbin.org:80": 1
+      },
+      "type": "roundrobin"
+    }
+  }'
 ```
 
-## 示例用法
-
-现在,如果您向 APISIX 发出请求,该请求将被记录在您的 Loki 服务器中:
+使用满足条件的 URL 查询字符串向路由发送请求:
 
 ```shell
-curl -i http://127.0.0.1:9080/hello
+curl -i "http://127.0.0.1:9080/anything?log_body=yes"; -X POST -d '{"env": 
"dev"}'
 ```
 
-## 删除插件
+您应该会收到 `HTTP/1.1 200 OK` 响应。
 
-当您需要删除 `loki-logger` 插件时,您可以使用以下命令删除相应的 JSON 配置,APISIX 将自动重新加载相关配置,而无需重启服务:
+导航到 [Grafana explore view](http://localhost:3000/explore) 并重新运行查询 `job = 
apisix`。您应该会看到与您的请求相对应的日志条目,与路由上配置的格式一致,类似于以下内容:
+
+```json
+{
+  "route_id": "loki-logger-route",
+  ...,
+  "request": {
+    "headers": {
+      ...
+    },
+    "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"
+  },
+  "latency": 809.99994277954
+}
+```
+
+向路由发送一个没有任何 URL 查询字符串的请求:
 
 ```shell
-curl http://127.0.0.1:9180/apisix/admin/routes/1  -H "X-API-KEY: $admin_key" 
-X PUT -d '
+curl -i "http://127.0.0.1:9080/anything"; -X POST -d '{"env": "dev"}'
+```
+
+您应该会收到 `HTTP/1.1 200 OK` 响应。
+
+导航到 [Grafana explore view](http://localhost:3000/explore) 并重新运行查询 `job = 
apisix`。您应该会看到与您的请求相对应的日志条目,与路由上配置的格式一致,类似于以下内容:
+
+```json
 {
-    "methods": ["GET"],
-    "uri": "/hello",
-    "plugins": {},
-    "upstream": {
-        "type": "roundrobin",
-        "nodes": {
-            "127.0.0.1:1980": 1
-        }
-    }
-}'
+  "route_id": "loki-logger-route",
+  ...,
+  "request": {
+    "headers": {
+      ...
+    },
+    "size": 169,
+    "method": "POST",
+    "url": "http://127.0.0.1:9080/anything";,
+    "querystring": {},
+    "uri": "/anything"
+  },
+  "latency": 557.00016021729
+}
+```
+
+:::info
+
+如果您除了将 `include_req_body` 或 `include_resp_body` 设置为 `true` 之外还自定义了 
`log_format`,则插件不会在日志中包含正文。
+
+作为一种解决方法,您可以在日志格式中使用 NGINX 变量 `$request_body`,例如:
+
+```json
+{
+  "kafka-logger": {
+    ...,
+    "log_format": {"body": "$request_body"}
+  }
+}
 ```
 
+:::
+
 ## FAQ
 
 ### 日志未正确推送


Reply via email to