Log Consumer Label in Access Log
Logging consumer labels in API Gateway's access log allows for more visibility and control over API traffic. By capturing consumer labels, organizations can easily identify which clients are accessing specific routes, track usage patterns, and enforce security policies based on these labels.
This guide will walk you through how to log consumer labels in the gateway's access log.
Prerequisites
Create and Use the New Variable in Access Log
In the gateway's configuration file, initialize a custom variable for the consumer label and assign it a default value -
. In this example, you will initialize a variable called $consumer_company
, but you could always initialize more as needed:
nginx_config:
http_server_location_configuration_snippet: |
set $consumer_company "-";
In the same file, update the access log format to include the newly initialized variable:
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"
Reload the gateway for changes to take effect.
Assign Value to the New Variable
Use serverless functions to assign consumer label value to the new variable.
For instance, configure the serverless-pre-function
plugin as a global plugin with the following configuration:
{
"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"
]
}
The function obtains the consumer label company
value and assigns it to consumer_company
variable. If the consumer does not have a company
label, the consumer_company
variable value will be assigned unknown
.
Configure Consumer and Authentication
Create a consumer named john
with label company: smart-technology
, and configure the key authentication credential for the consumer to be john-key
.
Next, create a route ane enable key authentication
Verify
send a request to the route with the valid key:
curl -i "http://127.0.0.1:9080/anything" -H 'apikey: john-key'
You should receive an HTTP/1.1 200 OK
response and see the following in the access log, where the company name is logged as smart-technology
:
192.168.107.1 - - [18/Mar/2025:09:17:28 +0000] 127.0.0.1:9080 "GET /anything HTTP/1.1" 200 508 1.260 "-" "curl/8.6.0" 13.210.43.76:80 200 1.153 "http://127.0.0.1:9080" "smart-technology"
send a request to the route without the key:
curl -i "http://127.0.0.1:9080/anything"
You should see an HTTP/1.1 401 Unauthorized
response and see the following in the access log, where the company name is logged as unknown
:
192.168.107.1 - - [18/Mar/2025:09:18:27 +0000] 127.0.0.1:9080 "GET /anything HTTP/1.1" 401 52 0.000 "-" "curl/8.6.0" - - - "http://127.0.0.1:9080" "unknown"