
我正在嘗試設置一個自我管理的 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
嗯,我終於做到了。
使用 yml 或環境變數既不必要也不充分,因為真實的客戶端 IP 和使用者代理程式不是靜態的。
我首先將 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 標頭 =)