1.4 KiB · text History bbb2a48
defmodule Vigil.LogsFixtures do
  @moduledoc """
  Log lines sent through the real ingest pipeline (`Ingest.accept` then
  `Drain.drain`), so the processor stores and broadcasts them.
  """

  import Vigil.PerformanceFixtures, only: [send_item: 3]

  @doc """
  A sentry-elixir style line, for `send_logs/2`. Options: `level`
  ("info"), `env` ("prod"), `service`, `host` ("web-1"), `trace`, `attrs`
  (extra attributes, plain values), `at` (a DateTime, now).
  """
  def log_line(body, opts \\ []) do
    at = Keyword.get(opts, :at, DateTime.utc_now())

    attrs =
      %{
        "sentry.environment" => opts |> Keyword.get(:env, "prod"),
        "sentry.release" => "shop@1.2",
        "sentry.address" => Keyword.get(opts, :host, "web-1")
      }
      |> Map.merge(if s = opts[:service], do: %{"service.name" => s}, else: %{})
      |> Map.merge(Keyword.get(opts, :attrs, %{}))
      |> Map.new(fn {k, v} -> {k, typed(v)} end)

    %{
      "timestamp" => DateTime.to_unix(at, :microsecond) / 1_000_000,
      "level" => Keyword.get(opts, :level, "info"),
      "body" => body,
      "trace_id" => opts[:trace],
      "span_id" => nil,
      "attributes" => attrs
    }
  end

  @doc "Sends lines (`log_line/2` maps) in one `log` item and drains."
  def send_logs(project, lines), do: send_item(project, "log", %{"items" => lines})

  defp typed(v) when is_integer(v), do: %{"value" => v, "type" => "integer"}
  defp typed(v), do: %{"value" => v, "type" => "string"}
end