Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Example Scout Mongo.Ecto Instrumentation
defmodule YourApp.Repo do
use Ecto.Repo
# Scout instrumentation of Mongo queries. These appear in traces as "Ecto/Read", "Ecto/Write", etc.
def log(entry) do
record(entry)
super entry
end
# Example `entry`:
# %Ecto.LogEntry{connection_pid: nil, params: [], query: #Function<8.67081969/1 in Mongo.Ecto.log/6>, query_time: 1287, queue_time: 26, result: {:ok, %Mongo.ReadResult{cursor_id: 0, docs: [%{"_id" => #BSON.ObjectId<58fa20c7845aef570c3435a8>, "prcp" => 10.0}, %{"_id" => #BSON.ObjectId<58fba2b487d75f78cfcda81e>, "city" => "RMNP", "inserted_at" => #BSON.DateTime<2017-04-22T18:36:36Z>, "prcp" => 1.4, "updated_at" => #BSON.DateTime<2017-04-22T18:36:36Z>}, %{"_id" => #BSON.ObjectId<58fba3dd87d75f78cf3e64a6>, "city" => "RMNP", "inserted_at" => #BSON.DateTime<2017-04-22T18:41:33Z>, "prcp" => 1.4, "updated_at" => #BSON.DateTime<2017-04-22T18:41:33Z>}, %{"_id" => #BSON.ObjectId<58fbc7d287d75f8b9608d7b9>, "city" => "RMNP", "inserted_at" => #BSON.DateTime<2017-04-22T21:14:58Z>, "prcp" => 1.4, "updated_at" => #BSON.DateTime<2017-04-22T21:14:58Z>}, %{"_id" => #BSON.ObjectId<58fbc8bb87d75f8ccd63de22>, "city" => "RMNP", "inserted_at" => #BSON.DateTime<2017-04-22T21:18:51Z>, "prcp" => 1.4, "updated_at" => #BSON.DateTime<2017-04-22T21:18:51Z>}], from: 0, num: 5}}}
defp record(entry) do
ScoutApm.Tracing.track(
"Ecto",query_name(entry),
query_time_in_microseconds(entry),
:microseconds
)
end
defp query_name(entry) do
{_, result} = entry.result
result_struct_type = result.__struct__ |> inspect # ex: Mongo.ReadResult
matches = Regex.named_captures(~r/\.(?<name>\w+)Result/, result_struct_type)
if matches && matches["name"] do
matches["name"]
else
"Query"
end
end
defp query_time_in_microseconds(entry) do
raw_time = entry.query_time
microtime = System.convert_time_unit(raw_time, :native, :microseconds)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment