将访问日志发送到 Splunk
本指南介绍如何配置 Splunk HTTP Event Collector(HEC)并使用 splunk-hec-logging 插件发送 API7 网关访问日 志。
前置条件
- 已安装 API7 企业版并在网关组上运行 API;
- 可访问 Splunk 部署;
- 具有创建 HEC Token 的权限。
步骤一:在 Splunk 中启用 HEC
在 Splunk 中创建一个 HEC Token,并记录 Token 值、HEC 端点和目标索引。典型端点为:
https://<SPLUNK_HOST>:8088/services/collector/event
为网关访问日志创建专用索引,例如 gateway_access_logs。如果 Splunk 使用自签名证书,仅在测试环境中使用跳过证书验证的配置。
步骤二:启用插件
选项 A:按路由启用
下 面的 ADC 配置为一个路由启用插件:
adc.yaml
services:
- name: splunk-service
routes:
- name: splunk-route
uris:
- /anything/*
plugins:
splunk-hec-logging:
endpoint:
uri: "https://splunk.example.com:8088/services/collector/event"
token: "YOUR_HEC_TOKEN"
upstream:
type: roundrobin
nodes:
- host: httpbin.org
port: 80
weight: 1
adc sync -f adc.yaml
Admin API 配置如下:
# 创建 Service
curl -k "https://localhost:7443/apisix/admin/services/splunk-service?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{"name":"splunk-service","upstream":{"type":"roundrobin","nodes":[{"host":"httpbin.org","port":80,"weight":1}]}}'
# 创建启用插件的路由
curl -k "https://localhost:7443/apisix/admin/routes/splunk-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{"name":"splunk-route","service_id":"splunk-service","paths":["/anything/*"],"plugins":{"splunk-hec-logging":{"endpoint":{"uri":"https://splunk.example.com:8088/services/collector/event","token":"YOUR_HEC_TOKEN"}}}}'
选项 B:全局规则
全局规则会将插件应用到网关组处理的每个请求;仍需要至少一个路由匹配流量:
curl -k "https://localhost:7443/apisix/admin/global_rules/splunk-hec-logging?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"plugins": {
"splunk-hec-logging": {
"endpoint": {
"uri": "https://splunk.example.com:8088/services/collector/event",
"token": "YOUR_HEC_TOKEN"
}
}
}
}'
ADC 配置如下:
adc.yaml
global_rules:
splunk-hec-logging:
endpoint:
uri: "https://splunk.example.com:8088/services/collector/event"
token: "YOUR_HEC_TOKEN"
可选:自定义日志格式
使用插件元数据覆盖事件中的默认字段。值支持 NGINX $variable 语法:
curl -k "https://localhost:7443/apisix/admin/plugin_metadata/splunk-hec-logging?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"log_format": {
"method": "$request_method",
"uri": "$request_uri",
"status": "$status"
}
}'
使用 ADC 时,也可以通过以下插件元数据配置相同字段:
adc.yaml
plugin_metadata:
splunk-hec-logging:
log_format:
method: "$request_method"
uri: "$request_uri"
status: "$status"
adc sync -f adc.yaml
该元数据会应用于同一网关组中的所有 splunk-hec-logging 实例。
验证
发送测试请求:
curl -i "http://127.0.0.1:9080/anything/test"
在 Splunk 中使用你在步骤一选择的索引搜索,例如:
index=gateway_access_logs source="apache-apisix-splunk-hec-logging"
插件会批量发送事件,日志可能需要几秒钟才出现。