Logs: log items from both SDKs, search syntax, facets, live tail broadcast

60e74af · gmorell · 2026-12-02 03:21

18 files +549 -3

Files changed

modified config/config.exs
+2 −1
@@ -72,7 +72,8 @@ config :vigil, Vigil.Partitions,
72 72 # Spans are many and short-lived; their rollups last longer.
73 73 %{table: "spans", kind: :uuid7_daily, ahead_days: 3, keep_days: 14},
74 74 %{table: "transaction_counts", kind: :weekly, ahead_days: 21, keep_days: 90},
75 − %{table: "uptime_checks", kind: :uuid7_daily, ahead_days: 3, keep_days: 30}
75 + %{table: "uptime_checks", kind: :uuid7_daily, ahead_days: 3, keep_days: 30},
76 + %{table: "log_events", kind: :uuid7_daily, ahead_days: 3, keep_days: 30}
76 77 ]
77 78
78 79 # Configure the endpoint
modified lib/vigil/ingest/outcome.ex
+3 −2
@@ -1,7 +1,8 @@
1 1 defmodule Vigil.Ingest.Outcome do
2 2 @moduledoc """
3 3 An hourly count of dropped data: what SDKs say they discarded (`:client`,
4 − from `client_report` items) and what the edge refused (`:edge`), by
4 + from `client_report` items), what the edge refused (`:edge`), and what
5 + processing dropped (`:server`: logs too far from the server clock), by
5 6 category (`error`, `transaction`, `log_item`, …) and reason.
6 7 """
7 8 use Vigil.Schema
@@ -9,7 +10,7 @@ defmodule Vigil.Ingest.Outcome do
9 10 schema "outcomes" do
10 11 field :organization_id, Ecto.UUID
11 12 field :hour, :utc_datetime
12 − field :source, Ecto.Enum, values: [:client, :edge]
13 + field :source, Ecto.Enum, values: [:client, :edge, :server]
13 14 field :category, :string
14 15 field :reason, :string
15 16 field :quantity, :integer, default: 0
modified lib/vigil/ingest/processor.ex
+1 −0
@@ -19,6 +19,7 @@ defmodule Vigil.Ingest.Processor do
19 19 "transaction" => Vigil.Performance.Processor,
20 20 "span" => Vigil.Performance.Processor,
21 21 "check_in" => Vigil.Monitors.Processor,
22 + "log" => Vigil.Logs.Processor,
22 23 "user_report" => Vigil.Events.FeedbackProcessor,
23 24 "feedback" => Vigil.Events.FeedbackProcessor
24 25 }
added lib/vigil/logs.ex
+204 −0
@@ -0,0 +1,204 @@
1 +defmodule Vigil.Logs do
2 + @moduledoc """
3 + Reading a project's structured logs (`Vigil.Logs.Processor` writes
4 + them):
5 +
6 + * `search/3`, newest first, with filters and a cursor for older pages;
7 + * `parse_query/1`: the search box's syntax: words match the message
8 + (all of them, case-insensitively), `level:error` (or
9 + `level:warn,error`), `env:`/`environment:`, `service:`, `host:`,
10 + `release:`, `trace:<id>`, and any other `key:value` matches that
11 + attribute (`user.id:42`, `"http.route":/orders`). Quote values with
12 + spaces: `service:"billing api"`. A leading `-` negates a word or a
13 + filter.
14 + * `facets/2`: levels, environments and services seen recently, with
15 + counts, for filter menus;
16 + * the live tail: new lines are broadcast on `"logs:<project_id>"` as
17 + `{:logs, [%LogEvent{}]}` (`subscribe/1`).
18 + """
19 +
20 + import Ecto.Query
21 +
22 + alias Vigil.Logs.LogEvent
23 + alias Vigil.Repo
24 +
25 + @columns %{
26 + "level" => :level,
27 + "env" => :environment,
28 + "environment" => :environment,
29 + "service" => :service,
30 + "host" => :host,
31 + "release" => :release,
32 + "trace" => :trace_id,
33 + "trace_id" => :trace_id
34 + }
35 +
36 + @levels ~w(trace debug info warn error fatal)
37 +
38 + @doc "Sentry's log levels, least severe first."
39 + def levels, do: @levels
40 +
41 + ## Live tail
42 +
43 + def subscribe(project_id), do: Phoenix.PubSub.subscribe(Vigil.PubSub, "logs:#{project_id}")
44 +
45 + @doc false
46 + def broadcast(project_id, rows) do
47 + events = rows |> Enum.take(-200) |> Enum.map(&struct(LogEvent, &1))
48 + Phoenix.PubSub.broadcast(Vigil.PubSub, "logs:#{project_id}", {:logs, events})
49 + end
50 +
51 + @doc """
52 + Whether a live-tail line matches parsed `filters` (`parse_query/1`), so
53 + the tail can show only what the current search would.
54 + """
55 + def matches?(%LogEvent{} = e, filters) do
56 + Enum.all?(filters, fn
57 + {:text, word, neg?} ->
58 + String.contains?(String.downcase(e.body || ""), String.downcase(word)) != neg?
59 +
60 + {:column, :level, values, neg?} ->
61 + e.level in values != neg?
62 +
63 + {:column, col, values, neg?} ->
64 + to_string(Map.get(e, col)) in values != neg?
65 +
66 + {:attr, key, values, neg?} ->
67 + to_string(Map.get(e.attributes || %{}, key)) in values != neg?
68 + end)
69 + end
70 +
71 + ## Searching
72 +
73 + @doc """
74 + The search box's text as filters: `[{:text, word, negated?} |
75 + {:column, field, [values], negated?} | {:attr, key, [values], negated?}]`.
76 + """
77 + def parse_query(nil), do: []
78 +
79 + def parse_query(q) when is_binary(q) do
80 + ~r/(-?)(?:("(?:[^"\\]|\\.)*"|[^\s:"]+):("(?:[^"\\]|\\.)*"|\S+)|("(?:[^"\\]|\\.)*"|\S+))/u
81 + |> Regex.scan(q)
82 + |> Enum.flat_map(fn
83 + [_, neg, key, value] when key != "" -> [term(dequote(key), dequote(value), neg == "-")]
84 + [_, neg, "", "", word] -> [{:text, dequote(word), neg == "-"}]
85 + _ -> []
86 + end)
87 + |> Enum.reject(&match?({:text, "", _}, &1))
88 + end
89 +
90 + defp term(key, value, neg?) do
91 + values = value |> String.split(",", trim: true) |> Enum.map(&String.trim/1)
92 +
93 + case Map.fetch(@columns, String.downcase(key)) do
94 + {:ok, :level} -> {:column, :level, Enum.map(values, &normalize_level/1), neg?}
95 + {:ok, :trace_id} -> {:column, :trace_id, Enum.map(values, &String.downcase/1), neg?}
96 + {:ok, col} -> {:column, col, values, neg?}
97 + :error -> {:attr, key, values, neg?}
98 + end
99 + end
100 +
101 + defp normalize_level("warning"), do: "warn"
102 + defp normalize_level(l), do: String.downcase(l)
103 +
104 + defp dequote("\"" <> _ = quoted) do
105 + quoted |> String.slice(1..-2//1) |> String.replace(~S(\"), ~S("))
106 + end
107 +
108 + defp dequote(s), do: s
109 +
110 + @doc """
111 + A project's logs matching `filters` (from `parse_query/1`), newest
112 + first. Options: `limit` (100), `before` (a log id: older than it, for
113 + "load more"), `since` (a DateTime).
114 + """
115 + def search(project_id, filters \\ [], opts \\ []) do
116 + limit = Keyword.get(opts, :limit, 100)
117 +
118 + from(e in LogEvent,
119 + where: e.project_id == ^project_id,
120 + order_by: [desc: e.id],
121 + limit: ^limit
122 + )
123 + |> before(opts[:before])
124 + |> since(opts[:since])
125 + |> apply_filters(filters)
126 + |> Repo.all()
127 + end
128 +
129 + defp before(query, nil), do: query
130 + defp before(query, id), do: where(query, [e], e.id < ^id)
131 +
132 + defp since(query, nil), do: query
133 +
134 + defp since(query, %DateTime{} = at),
135 + do: where(query, [e], e.id >= ^Vigil.Partitions.uuid7_floor(at))
136 +
137 + defp apply_filters(query, filters) do
138 + Enum.reduce(filters, query, fn
139 + {:text, word, false}, q ->
140 + where(q, [e], ilike(e.body, ^"%#{like(word)}%"))
141 +
142 + {:text, word, true}, q ->
143 + where(q, [e], not ilike(e.body, ^"%#{like(word)}%"))
144 +
145 + {:column, col, values, false}, q ->
146 + where(q, [e], field(e, ^col) in ^values)
147 +
148 + {:column, col, values, true}, q ->
149 + where(q, [e], is_nil(field(e, ^col)) or field(e, ^col) not in ^values)
150 +
151 + {:attr, key, values, false}, q ->
152 + where(q, [e], fragment("?->>?", e.attributes, ^key) in ^values)
153 +
154 + {:attr, key, values, true}, q ->
155 + where(
156 + q,
157 + [e],
158 + is_nil(fragment("?->>?", e.attributes, ^key)) or
159 + fragment("?->>?", e.attributes, ^key) not in ^values
160 + )
161 + end)
162 + end
163 +
164 + defp like(q), do: String.replace(q, ~w(\\ % _), &"\\#{&1}")
165 +
166 + @doc "One log line of a project, or nil."
167 + def get_log(project_id, id) do
168 + with {:ok, id} <- Ecto.UUID.cast(id),
169 + do: Repo.get_by(LogEvent, id: id, project_id: project_id),
170 + else: (_ -> nil)
171 + end
172 +
173 + @doc """
174 + Levels, environments and services in a project's logs over the last
175 + `hours` (24), each a list of `{value, count}`, most first.
176 + """
177 + def facets(project_id, hours \\ 24) do
178 + since = Vigil.Partitions.uuid7_floor(DateTime.add(DateTime.utc_now(), -hours * 3600))
179 +
180 + for {name, col} <- [level: :level, environment: :environment, service: :service], into: %{} do
181 + rows =
182 + Repo.all(
183 + from e in LogEvent,
184 + where: e.project_id == ^project_id and e.id >= ^since and not is_nil(field(e, ^col)),
185 + group_by: field(e, ^col),
186 + order_by: [desc: count(e.id)],
187 + limit: 20,
188 + select: {field(e, ^col), count(e.id)}
189 + )
190 +
191 + {name, rows}
192 + end
193 + end
194 +
195 + @doc "The logs of a trace across the given (visible) projects, oldest first."
196 + def for_trace(project_ids, trace_id, limit \\ 500) do
197 + Repo.all(
198 + from e in LogEvent,
199 + where: e.project_id in ^project_ids and e.trace_id == ^String.downcase(trace_id),
200 + order_by: [asc: e.timestamp],
201 + limit: ^limit
202 + )
203 + end
204 +end
added lib/vigil/logs/log_event.ex
+28 −0
@@ -0,0 +1,28 @@
1 +defmodule Vigil.Logs.LogEvent do
2 + @moduledoc """
3 + One structured log line (`log` items, sentry-elixir and sentry-python),
4 + in `log_events`, partitioned by day on `id` (UUIDv7: when it was
5 + stored). `level` is Sentry's (trace, debug, info, warn, error, fatal);
6 + `service`, `environment`, `release` and `host` come out of the
7 + attributes for filtering; `attributes` holds the rest, flattened to
8 + plain values.
9 + """
10 + use Vigil.Schema
11 +
12 + schema "log_events" do
13 + field :organization_id, Ecto.UUID
14 + field :timestamp, :utc_datetime_usec
15 + field :level, :string
16 + field :severity_number, :integer
17 + field :body, :string
18 + field :trace_id, :string
19 + field :span_id, :string
20 + field :environment, :string
21 + field :release, :string
22 + field :service, :string
23 + field :host, :string
24 + field :attributes, :map, default: %{}
25 +
26 + belongs_to :project, Vigil.Projects.Project
27 + end
28 +end
added lib/vigil/logs/processor.ex
+116 −0
@@ -0,0 +1,116 @@
1 +defmodule Vigil.Logs.Processor do
2 + @moduledoc """
3 + `log` items into `log_events`: `{"items": [...]}` (sentry-elixir) or
4 + with `"version": 2` (sentry-python), each `{timestamp, level, body,
5 + trace_id, span_id, attributes: {key: {value, type}}}`.
6 +
7 + Lines whose timestamp is more than a day from the server's clock are
8 + dropped and counted as a `:server` outcome (`log_item`, `timestamp`).
9 + New lines are broadcast on `"logs:<project_id>"` for the live tail.
10 + """
11 + @behaviour Vigil.Ingest.Processor
12 +
13 + alias Vigil.Ingest.{BufferedItem, Outcomes}
14 + alias Vigil.Logs
15 + alias Vigil.Logs.LogEvent
16 + alias Vigil.Repo
17 +
18 + @max_items 1000
19 + @max_body 16_384
20 + @skew_seconds 86_400
21 +
22 + @impl true
23 + def process(%BufferedItem{} = item) do
24 + case Jason.decode(item.payload) do
25 + {:ok, %{"items" => items}} when is_list(items) ->
26 + now = DateTime.utc_now()
27 +
28 + {rows, dropped} =
29 + items |> Enum.take(@max_items) |> Enum.map(&row(item, &1, now)) |> split()
30 +
31 + rows |> Enum.chunk_every(500) |> Enum.each(&Repo.insert_all(LogEvent, &1))
32 +
33 + if dropped > 0,
34 + do: Outcomes.record(item, :server, "log_item", "timestamp", dropped, now)
35 +
36 + if rows != [], do: Logs.broadcast(item.project_id, rows)
37 + :ok
38 +
39 + _ ->
40 + :ok
41 + end
42 + end
43 +
44 + defp split(results) do
45 + Enum.reduce(results, {[], 0}, fn
46 + {:ok, row}, {rows, n} -> {[row | rows], n}
47 + :drop, {rows, n} -> {rows, n + 1}
48 + end)
49 + |> then(fn {rows, n} -> {Enum.reverse(rows), n} end)
50 + end
51 +
52 + defp row(item, %{} = log, now) do
53 + with %DateTime{} = at <- Vigil.Performance.Normalize.time(log["timestamp"]),
54 + true <- abs(DateTime.diff(at, now)) <= @skew_seconds do
55 + attrs = flatten(log["attributes"])
56 +
57 + {:ok,
58 + %{
59 + id: Vigil.Schema.uuid7(),
60 + project_id: item.project_id,
61 + organization_id: item.organization_id,
62 + timestamp: at,
63 + level: level(log["level"], attrs),
64 + severity_number: severity(attrs["sentry.severity_number"]),
65 + body: log["body"] |> to_string() |> String.slice(0, @max_body),
66 + trace_id: hex(log["trace_id"], 32),
67 + span_id: hex(log["span_id"], 16),
68 + environment: str(attrs["sentry.environment"] || attrs["deployment.environment"], 255),
69 + release: str(attrs["sentry.release"] || attrs["service.version"], 250),
70 + service: str(attrs["service.name"] || attrs["sentry.sdk.name"], 255),
71 + host: str(attrs["server.address"] || attrs["sentry.address"] || attrs["host.name"], 255),
72 + attributes: attrs
73 + }}
74 + else
75 + _ -> :drop
76 + end
77 + end
78 +
79 + defp row(_item, _log, _now), do: :drop
80 +
81 + defp flatten(%{} = attrs) do
82 + attrs
83 + |> Enum.take(200)
84 + |> Map.new(fn
85 + {k, %{"value" => v}} -> {String.slice(to_string(k), 0, 200), v}
86 + {k, v} -> {String.slice(to_string(k), 0, 200), v}
87 + end)
88 + end
89 +
90 + defp flatten(_), do: %{}
91 +
92 + # Sentry's levels; Elixir sends "warning", and severity text may differ.
93 + @levels ~w(trace debug info warn error fatal)
94 + defp level(l, attrs) do
95 + case String.downcase(to_string(l || attrs["sentry.severity_text"] || "info")) do
96 + l when l in @levels -> l
97 + "warning" -> "warn"
98 + l when l in ~w(critical alert emergency) -> "fatal"
99 + "notice" -> "info"
100 + _ -> "info"
101 + end
102 + end
103 +
104 + defp severity(n) when is_integer(n) and n in 1..24, do: n
105 + defp severity(_), do: nil
106 +
107 + defp hex(v, len) when is_binary(v) do
108 + v = String.downcase(v)
109 + if byte_size(v) == len and v =~ ~r/\A[0-9a-f]+\z/, do: v
110 + end
111 +
112 + defp hex(_, _), do: nil
113 +
114 + defp str(v, max) when is_binary(v) and v != "", do: String.slice(v, 0, max)
115 + defp str(_, _), do: nil
116 +end
added priv/repo/migrations/20261202031933_create_log_events.exs
+42 −0
@@ -0,0 +1,42 @@
1 +defmodule Vigil.Repo.Migrations.CreateLogEvents do
2 + use Ecto.Migration
3 +
4 + # Slice 9 (ROADMAP.md): structured logs, partitioned by UUIDv7 id (a
5 + # partition a day). Service, environment, host and level are columns for
6 + # filtering; everything else stays in `attributes`.
7 + def up do
8 + execute """
9 + CREATE TABLE log_events (
10 + id uuid NOT NULL,
11 + project_id uuid NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
12 + organization_id uuid NOT NULL,
13 + timestamp timestamp(6) NOT NULL,
14 + level varchar(16) NOT NULL,
15 + severity_number smallint,
16 + body text NOT NULL,
17 + trace_id varchar(32),
18 + span_id varchar(16),
19 + environment varchar(255),
20 + release varchar(250),
21 + service varchar(255),
22 + host varchar(255),
23 + attributes jsonb NOT NULL DEFAULT '{}',
24 + PRIMARY KEY (id)
25 + ) PARTITION BY RANGE (id)
26 + """
27 +
28 + execute "CREATE INDEX log_events_project_id_index ON log_events (project_id, id DESC)"
29 +
30 + execute """
31 + CREATE INDEX log_events_project_trace_index ON log_events (project_id, trace_id)
32 + WHERE trace_id IS NOT NULL
33 + """
34 +
35 + # Substring search on the message (ILIKE), with pg_trgm (slice 2).
36 + execute "CREATE INDEX log_events_body_trgm_index ON log_events USING gin (body gin_trgm_ops)"
37 + end
38 +
39 + def down do
40 + execute "DROP TABLE log_events"
41 + end
42 +end
added test/vigil/logs_test.exs
+153 −0
@@ -0,0 +1,153 @@
1 +defmodule Vigil.LogsTest do
2 + use Vigil.DataCase, async: true
3 +
4 + import Vigil.AccountsFixtures
5 + import Vigil.OrganizationsFixtures
6 +
7 + alias Vigil.{Ingest, Logs}
8 + alias Vigil.Ingest.{Drain, Envelope}
9 + alias Vigil.Logs.LogEvent
10 +
11 + @trace "0af7651916cd43dd8448eb211c80319c"
12 +
13 + setup do
14 + owner = user_fixture()
15 + org = organization_fixture(owner)
16 + project = project_fixture(org_scope(owner, org))
17 +
18 + target = %Ingest.Target{
19 + project_id: project.id,
20 + dsn_id: project.dsn_id,
21 + organization_id: org.id,
22 + key_id: Ecto.UUID.generate()
23 + }
24 +
25 + %{project: project, target: target}
26 + end
27 +
28 + defp send_logs(target, payload) do
29 + item = %Envelope.Item{
30 + type: "log",
31 + headers: %{"type" => "log"},
32 + payload: Jason.encode!(payload)
33 + }
34 +
35 + Ingest.accept(target, %{headers: %{}, items: [item]}, %{client_ip: nil, user_agent: nil})
36 + Drain.drain(target.project_id)
37 + end
38 +
39 + defp attr(v) when is_integer(v), do: %{"value" => v, "type" => "integer"}
40 + defp attr(v), do: %{"value" => v, "type" => "string"}
41 + defp now, do: DateTime.to_unix(DateTime.utc_now(), :microsecond) / 1_000_000
42 +
43 + # sentry-elixir: no version; "warning"; environment and address attributes.
44 + defp elixir_log(body, level, extra \\ %{}) do
45 + %{
46 + "timestamp" => now(),
47 + "level" => level,
48 + "body" => body,
49 + "trace_id" => @trace,
50 + "span_id" => nil,
51 + "attributes" =>
52 + Map.merge(
53 + %{
54 + "sentry.sdk.name" => attr("sentry.elixir"),
55 + "sentry.environment" => attr("prod"),
56 + "sentry.release" => attr("shop@1.2"),
57 + "sentry.address" => attr("web-1")
58 + },
59 + extra
60 + )
61 + }
62 + end
63 +
64 + test "sentry-elixir and sentry-python logs are stored, flattened, and filterable", ctx do
65 + send_logs(ctx.target, %{
66 + "items" => [
67 + elixir_log("order 42 placed", "info", %{"order.id" => attr(42)}),
68 + elixir_log("payment declined for order 42", "warning", %{
69 + "service.name" => attr("billing")
70 + })
71 + ]
72 + })
73 +
74 + send_logs(ctx.target, %{
75 + "version" => 2,
76 + "items" => [
77 + %{
78 + "timestamp" => now(),
79 + "level" => "error",
80 + "body" => "worker crashed",
81 + "attributes" => %{
82 + "sentry.severity_number" => attr(17),
83 + "sentry.environment" => attr("staging"),
84 + "server.address" => attr("py-1")
85 + }
86 + }
87 + ]
88 + })
89 +
90 + [crashed, declined, placed] = Logs.search(ctx.project.id)
91 +
92 + assert {placed.level, placed.environment, placed.release, placed.host} ==
93 + {"info", "prod", "shop@1.2", "web-1"}
94 +
95 + assert placed.attributes["order.id"] == 42
96 + assert placed.trace_id == @trace
97 + assert declined.level == "warn" and declined.service == "billing"
98 + assert crashed.level == "error" and crashed.severity_number == 17 and crashed.host == "py-1"
99 +
100 + q = &Logs.search(ctx.project.id, Logs.parse_query(&1))
101 + assert [%{body: "worker crashed"}] = q.("level:error")
102 + assert [_, _] = q.("level:warn,error")
103 + assert [_, _] = q.("ORDER 42")
104 + assert [%{body: "order 42 placed"}] = q.("order -declined")
105 + assert [_, _] = q.("env:prod")
106 + assert [%{body: "payment" <> _}] = q.("service:billing")
107 + assert [%{body: "order 42 placed"}] = q.("order.id:42")
108 + assert [_, _] = q.("trace:#{String.upcase(@trace)}")
109 + assert [_] = q.("-env:prod")
110 +
111 + assert %{level: levels, environment: envs} = Logs.facets(ctx.project.id)
112 + assert {"prod", 2} in envs
113 + assert length(levels) == 3
114 +
115 + # Older pages.
116 + assert [^declined, ^placed] = Logs.search(ctx.project.id, [], before: crashed.id)
117 + assert [_, _] = Logs.for_trace([ctx.project.id], @trace)
118 + end
119 +
120 + test "lines more than a day off the server clock are dropped and counted", ctx do
121 + old = elixir_log("ancient", "info") |> Map.put("timestamp", now() - 3 * 86_400)
122 + send_logs(ctx.target, %{"items" => [old, elixir_log("fresh", "info")]})
123 +
124 + assert [%{body: "fresh"}] = Logs.search(ctx.project.id)
125 +
126 + assert [%{source: :server, category: "log_item", reason: "timestamp", quantity: 1}] =
127 + Repo.all(Vigil.Ingest.Outcome)
128 + end
129 +
130 + test "new lines are broadcast for the live tail, and match the search filters", ctx do
131 + Logs.subscribe(ctx.project.id)
132 + send_logs(ctx.target, %{"items" => [elixir_log("hello tail", "error")]})
133 + assert_receive {:logs, [%LogEvent{body: "hello tail"} = e]}
134 +
135 + assert Logs.matches?(e, Logs.parse_query("level:error tail"))
136 + refute Logs.matches?(e, Logs.parse_query("level:info"))
137 + refute Logs.matches?(e, Logs.parse_query("-tail"))
138 + assert Logs.matches?(e, Logs.parse_query(~s(host:"web-1")))
139 + end
140 +
141 + test "parse_query" do
142 + assert [
143 + {:text, "timeout", false},
144 + {:column, :level, ["warn", "error"], false},
145 + {:column, :service, ["billing api"], false},
146 + {:attr, "http.route", ["/orders"], true},
147 + {:text, "two words", false}
148 + ] =
149 + Logs.parse_query(
150 + ~s(timeout level:warning,error service:"billing api" -http.route:/orders "two words")
151 + )
152 + end
153 +end

Parents: 4cd4d66