集成 nginx 日志和 elasticsearch app-search

集成 nginx 日志和 elasticsearch app-search

我正在尝试设置一个自我管理的 docker appsearch 实例,与 kibana 和 elasticsearch 一起,由 uvicorn python 应用程序查询,由 nginx 网络服务器代理

我当前的问题是,appsearch 日志在 appsearch 日志中显示 python 默认用户代理和 IP(即 python-requests/2.22.0 和 LAN IP)。

我想将包含远程客户端的正确 IP 和用户代理的 nginx 自定义标头转发到可在 kibana 中很好地查询的 appsearch 日志。

我注意到可以output.elasticsearch.headers在环境或 filebeat.yml 中设置为自定义标题。

你们对此有什么想法吗?

谢谢。

答案1

嗯,我终于做到了。

由于真实客户端 IP 和用户代理不是静态的,因此使用 yml 或环境变量没有必要也不够。

我首先将 nginx.conf 代理更改为:

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-User-Agent $http_user_agent;

然后在每个 uvicorn FastAPI 方法中我添加了第一个request参数:

from fastapi import FastAPI
app = FastAPI()
# ...
@app.get("/search")
async def search_endpoint(request: Request):
# ... method implementation 

search_endpoint 调用我的搜索类,而我的搜索类又使用 appsearch 的 python 客户端:

import elastic_app_search
# ...
client = elastic_app_search.Client(api_key = XXX, base_endpoint = YYY, use_https=False)

然后在客户端更新标题:

x_headers = {
    'Connection': 'close',
    'X-Forwarded-For': request.headers['X-Forwarded-For'],
    'X-User-Agent': request.headers['X-User-Agent']
}
client.session.session.headers.update(x_headers)
# For current appsearch python client the repeated name was necessary

然后应用程序日志开始记录自定义 X-headers =)

相关内容