我在凤凰应用程序中有以下api客户端。
defmodule SomeService do
use HTTPoison.Base
def process_request_url(url) do
Application.get_env(:my_app, :some_service)[:host] <> url
end
def process_response_body(body) do
if String.trim(body) != "" do
body
|> Poison.decode! # this could fail if the response is html
|> Enum.map(fn({k, v}) -> {String.to_atom(k), v} end)
|> Enum.into(%{})
else
body
end
end
def get_some_data(customer_id, access_token) do
path = "/customer/#{customer_id}/"
headers = [{"Authorization", "Bearer #{access_token}"}]
case get(path, headers) do
{:ok, %HTTPoison.Response{body: body}} ->
{:ok, body}
{:error, error} -> {:error, error}
_ -> {:error, "unknown error from upstream system"}
end
end
end监视传出API调用的最佳方法是什么?
我们正在使用遥测技术来监控传入的请求和ECTO查询。然而,HTTPoison似乎没有提供即时遥测事件,我们如何利用遥测技术来实现这一目标呢?
发布于 2020-01-30 08:01:11
现在,我使用响应数据来提高遥测事件,如下所示:
defmodule SomeService do
use HTTPoison.Base
def process_request_url(url) do
Application.get_env(:my_app, :some_service)[:host] <> url
end
def process_response_body(body) do
if String.trim(body) != "" do
body
|> Poison.decode! # this could fail if the response is html
|> Enum.map(fn({k, v}) -> {String.to_atom(k), v} end)
|> Enum.into(%{})
else
body
end
end
def get_some_data(customer_id, access_token) do
path = "/customer/#{customer_id}/"
headers = [{"Authorization", "Bearer #{access_token}"}]
case get(path, headers) do
{:ok, %HTTPoison.Response{body: body}} ->
:telemetry.execute(
[:my_app, :upstream_endpoint],
%{request_path: response.request_url,
status_code: response.status_code,
response_headers: response.headers
},
response
)
{:ok, body}
{:error, error} -> {:error, error}
_ -> {:error, "unknown error from upstream system"}
end
end
endresponse对象包含需要监视的所有信息(url、状态、持续时间等),并将其记录在处理程序中。
def handle_event([:my_app, :upstream_endpoint], measurements, metadata, config) do
summary_event = []
|> Keyword.put(:route_url, measurements.request_path)
|> Keyword.put(:status_code, measurements.status_code)
|> Keyword.put(:response_headers, Enum.into(measurements.response_headers, %{}))
Logger.info("upstream-call", summary_event)
end事件:my_app,:upstream_endpoint附加到应用程序启动中的处理程序。
:telemetry.attach("may-app", [:my_app, :upstream_endpoint], &handle_event/4, %{})虽然目前这是很好的工作,但是对于每个api调用,都需要紧急地引发事件,而不是非常可扩展的。
https://stackoverflow.com/questions/59973248
复制相似问题