在访问日志中记录消费者标签
在 APISIX 的访问日志中记录消费者标签可以提高 API 流量的可见性和控制力。通过捕获消费者标签,组织可以轻松识别哪些客户端正在访问特定路由,跟踪使用模式,并根据这些标签实施安全策略。
本指南将向你展示如何在网关的访问日志中记录消费者标签。
备注
Ingress Controller 目前不支持配置消费者标签。
前置条件
创建并在访问日志中使用新变量
在 配置文件 中,为消费者标签初始化一个自定义变量,并为其分配默认值 -。在此示例中,你将初始化一个名为 $consumer_company 的变量,但你始终可以根据需要初始化更多变量:
conf/config.yaml
nginx_config:
http_server_location_configuration_snippet: |
set $consumer_company "-";
在同一文件中,更新访问日志格式以包含新初始化的变量:
conf/config.yaml
nginx_config:
http:
access_log_format: >-
$remote_addr - $remote_user [$time_local] $http_host \"$request\" $status $body_bytes_sent $request_time \"$http_referer\" \"$http_user_agent\" $upstream_addr $upstream_status $upstream_response_time \"$upstream_scheme://$upstream_host$upstream_uri\" "$consumer_company"
重新加载 APISIX 以使更改生效。
为新变量赋值
使用 无服务器函数 为新变量分配消费者标签值。
例如,将 serverless 插件配置为全局插件,如下所示:
curl "http://127.0.0.1:9180/apisix/admin/global_rules" -X PUT -d '
{
"id": "serverless-consumer-label",
"plugins": {
"serverless-pre-function": {
"phase": "log",
"functions": [
"return function (conf, ctx) ngx.var.consumer_company = ctx.consumer and ctx.consumer.labels and ctx.consumer.labels[\"company\"] or \"unknown\" end"
]
}
}
}'
该函数获取消费者标签 company 值并将其分配给 consumer_company 变量。如果消费者没有 company 标签,consumer_company 变量值将被分配为 unknown。