From da0638d1989d142af2a1045ae575b1368edd9613 Mon Sep 17 00:00:00 2001 From: Karl-Aksel Puulmann Date: Wed, 17 Jan 2024 14:27:00 +0200 Subject: [PATCH] Populate log_comment column with tags for performance analysis These tags include information like plausible.site.id and http.route. The tags will be exposed in system.query_log table log_comment column and can be used for query performance analysis. The tags are indirectly fetched from OpenTelemetry traces to avoid duplicating data. The fetching mechanism is clunky and the best I could figure out for now - help appreciated. --- lib/plausible/clickhouse_repo.ex | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/lib/plausible/clickhouse_repo.ex b/lib/plausible/clickhouse_repo.ex index f6f8631d9..22ef49920 100644 --- a/lib/plausible/clickhouse_repo.ex +++ b/lib/plausible/clickhouse_repo.ex @@ -25,4 +25,34 @@ defmodule Plausible.ClickhouseRepo do |> Enum.to_list() |> Keyword.values() end + + @doc """ + Automatically adds tags as query log_comment setting for clickhouse queries. + + These tags include information like plausible.site.id and http.route. + + The tags will be exposed in system.query_log table log_comment column and can be used + for query performance analysis. + + The tags are indirectly fetched from OpenTelemetry traces to avoid duplicating data. + """ + @impl true + def prepare_query(_operation, query, opts) do + setting = {:log_comment, Jason.encode!(current_trace_attributes())} + + opts = Keyword.update(opts, :settings, [setting], fn settings -> [setting | settings] end) + + {query, opts} + end + + defp current_trace_attributes() do + try do + :ets.tab2list(:otel_span_table) + |> Enum.at(0) + |> elem(9) + |> elem(4) + rescue + _ -> %{} + end + end end