Analyze the Logger backend in Elixir—how do you implement a custom backend to send logs…
- User
Analyze the
Loggerbackend in Elixir—how do you implement a custom backend to send logs to Slack? Assistant
Analyze the Logger backend in Elixir—how do you implement a custom backend to send logs to Slack?
1. Understand the Goal: The user wants to know how to implement a custom Logger backend in Elixir specifically to send logs to Slack.
Identify Key Concepts:
Logger application.GenEvent (historical context) vs. current :logger (OTP 21+). Correction: Elixir's Logger used to use GenEvent heavily but has moved towards a more direct handler approach, especially with OTP 21's new logger. However, Elixir's LoggerBackends behaviour (introduced in Elixir 1.15 or thereabouts, actually formalizing the old :gen_event pattern into a dedicated behaviour) is the standard way to build backends that fit into Elixir's config/config.exs structure.Structure the Answer:
LoggerBackends Behaviour: This is the core mechanism. I need to explain init, handle_event, handle_call, handle_info, terminate.LoggerBackends behaviour.config.exs.Drafting the Content - Step-by-Step:
Concept: Elixir's Logger allows multiple backends. A backend is essentially a GenServer that receives log messages.
The Behaviour: Since Elixir 1.11+, and specifically solidified recently, we use LoggerBackends.
init/1, handle_event/2, etc.The Slack Logic:
%{text: "message"}.The Code:
defmodule MySlackLogger do
@behaviour :gen_event # Wait, is it?
# Actually, for Elixir Logger, it's technically :gen_event under the hood, but Elixir wraps it.
# The modern way (Elixir 1.15+) suggests implementing LoggerBackends behaviour, or just following the :gen_event pattern if adding via config.
# Let's stick to the :gen_event interface because that is what the Logger module expects when you do `config :logger, :console, ...`.
# Wait, Elixir 1.15 introduced `LoggerBackends`.
# Let's check the docs mental model:
# `config :logger, :my_backend, MyModule`
# MyModule needs to implement :gen_event callbacks.
Refining the Behaviour Choice:
While Elixir 1.15 introduced LoggerBackends as a wrapper/helper, the underlying mechanism is still OTP's :gen_event. However, to keep it simple and robust for modern Elixir, implementing the :gen_event callbacks is the standard way to create a backend.
The handle_event callback: This is where the log comes in.
{:log, log_message_struct}.Formatting:
The HTTP Request:
Task or an async HTTP client like Finch or Req. Let's suggest Finch or HTTPoison (standard) but emphasize non-blocking.handle_event, high log volume will crash the node's logger process. I must spawn a task or use a pool.Batching (Advanced):
Writing the Code (Mental Draft):
defmodule MyApp.SlackBackend do
@behaviour :gen_event
def init({MyApp.SlackBackend, opts}) do
# check for webhook
{:ok, %{webhook: opts[:webhook]}}
end
def handle_event({:log, msg}, state) do
# format
# send async
{:ok, state}
end
end
Refinement on State: The Logger config usually looks like config :logger, MyApp.SlackBackend, webhook: "...".
Refining the Explanation:
Logger is an event manager.:gen_event Behaviour: This is the specific API required.:error).Structuring the Output:
:gen_event.config.exs.Review against "Analyze" request: The user asked to analyze how it works and how to implement. So I need to explain the internals (event flow) briefly before jumping to the code.
Logger.info. Logger forwards to LoggerBackends (the manager). The manager calls handle_event on every attached backend. The backend processes it.Self-Correction during drafting:
Formatting: The log message passed to handle_event is a map (in newer Elixir versions) or a tuple. Actually, :gen_event handlers for Logger receive a structure that needs to be inspected.
Correction: The :gen_event handler receives {level, group_leader, {Logger, message, timestamp, metadata}} or similar tuple formats depending on version.
Wait: Elixir 1.10+ changed the internal structure.
Standard approach: Use Logger.Formatter.
Better approach: The handle_event receives {:log, log_event}. The log_event struct has keys like level, msg, meta.
Actually, looking at standard LoggerBackends implementations (like logger_console_backend), they rely on LoggerBackends macro/behaviour in newer Elixir.
Let's stick to the raw :gen_event implementation as it is the most compatible and fundamental way.
Wait, Elixir 1.16 is out.
Let's ensure I provide the handle_call for configuration updates (hot reload).
Final Code Polish:
Req for HTTP because it's modern and standard in new Phoenix apps (or Finch + Req).Task to send the request so the logger doesn't block.IO.ANSI.strip/1) because Slack doesn't render terminal colors.Final Output Generation: (Proceeding to generate response based on these steps).
(Self-Correction on "Buffering"):
Implementing a true buffer (GenStage or similar) is complex for a basic example. I will implement a "Fire and Forget" approach using Task, but explicitly warn that for production, one should use a library like logger_slack_backend or implement a GenServer buffer to batch messages to avoid hitting Slack's 1req/sec per workspace limit (roughly).
Let's focus on the implementation logic requested.
Plan:
:gen_event.:gen_event behavior. Although Elixir's Logger interface feels like a standard module, the backend system is powered by an event manager.To implement a Slack backend, you need to create a module that listens for log events, formats them into a Slack-compatible JSON payload, and sends them via HTTP without blocking the application's execution.
Here is a guide on how to analyze the architecture and implement the backend.
:gen_eventThe Elixir Logger is a wrapper around an OTP :gen_event manager.
Logger.info("msg"), the Logger aggregates the metadata and broadcasts an event (:log) to all attached backends.To hook into this, your module must implement the :gen_event callbacks, specifically init/1, handle_event/2, and handle_call/2.
Here is a complete implementation of a Slack backend. This module handles configuration, formatting, and the asynchronous dispatch of messages.
Dependencies:
You will need an HTTP client. This example uses Req (popular in modern Elixir), but you can swap it for HTTPoison or Finch.
# lib/my_app/logger_slack_backend.ex
defmodule MyApp.LoggerSlackBackend do
@behaviour :gen_event
# Struct to hold the state of this backend
defstruct [:webhook_url, :level, :metadata]
# --- Callbacks ---
@impl true
def init({__MODULE__, opts}) do
# This is called when the backend is added to Logger.
# We fetch configuration from the opts passed in config.exs.
config = struct!(__MODULE__, opts)
# Ensure essential config exists
if is_nil(config.webhook_url) do
{:error, :missing_webhook_url}
else
{:ok, config}
end
end
@impl true
def handle_event({level, _pid, {Logger, msg, timestamp, metadata}}, state) do
# 1. Filter by Log Level
# Only proceed if the message level is severe enough for this backend.
if Logger.compare_levels(level, state.level) != :lt do
# 2. Format the Message
formatted_msg = format_message(level, msg, timestamp, metadata, state)
# 3. Dispatch to Slack (Async)
# We MUST spawn a task or use async here. Do not block the :gen_event loop
# with an HTTP request, or you will freeze the entire Logger system.
Task.start(fn -> send_to_slack(state.webhook_url, formatted_msg) end)
end
{:ok, state}
end
# Catch-all for other event types (like :error_report)
@impl true
def handle_event(_event, state), do: {:ok, state}
@impl true
def handle_call({:configure, new_opts}, state) do
# Allows hot-reloading config via Logger.configure_backend
new_state = struct!(state, new_opts)
{:ok, :ok, new_state}
end
# --- Private Logic ---
defp format_message(level, msg, timestamp, metadata, state) do
# 1. Format Timestamp
{:ok, time_str} = Calendar.DateTime.from_erl!(timestamp, "UTC") |> Calendar.DateTime.to_string()
# 2. Filter Metadata (optional)
# You might only want to show specific metadata like user_id or request_id
relevant_meta = take_metadata(metadata, state.metadata)
# 3. Construct Slack Attachment (JSON structure)
# Using "attachments" allows for colored borders based on level.
%{
attachments: [
%{
color: level_to_color(level),
title: "[#{String.upcase(to_string(level))}]",
text: "#{msg}\n\n*Metadata:* `#{inspect(relevant_meta)}`",
ts: :erlang.system_time(:second)
}
]
}
end
defp send_to_slack(webhook_url, payload) do
# Req is used here for the HTTP Post
case Req.post(webhook_url, json: payload) do
{:ok, _} -> :ok
{:error, reason} ->
# Avoid infinite loops: Do not use Logger.error here!
IO.puts("[SlackLogger] Failed to send log: #{inspect(reason)}")
end
end
# Helper: Map Elixir levels to Slack Hex Colors
defp level_to_color(:error), do: "#FF0000" # Red
defp level_to_color(:warn), do: "#FFA500" # Orange
defp level_to_color(:info), do: "#36a64f" # Green
defp level_to_color(_), do: "#CCCCCC" # Grey
# Helper: Filter metadata keys
defp take_metadata(metadata, :all), do: metadata
defp take_metadata(metadata, keys) when is_list(keys) do
Keyword.take(metadata, keys)
end
defp take_metadata(_, _), do: []
end
To activate this backend, you need to configure it in config/config.exs.
Key Configuration:
webhook_url: The Incoming Webhook URL from Slack.level: The minimum level to log (e.g., :error to only alert on crashes).metadata: Which keys to include (keep this small to avoid noise).# config/config.exs
config :logger, :backends,
[:console, {MyApp.LoggerSlackBackend, :slack_logger}]
config :logger, :slack_logger,
webhook_url: System.get_env("SLACK_WEBHOOK_URL"),
level: :error, # Only send errors and criticals to Slack
metadata: [:user_id, :request_id]
When implementing a backend for an external service like Slack, there are three specific failure modes you must handle to prevent crashing your application.
The handle_event/2 callback runs inside the Logger process. If you make a synchronous HTTP request here (e.g., Req.post!(...)), your application will pause every time it logs an error until the HTTP request finishes.
Task.start, Task.start_link (inside a supervisor), or a buffering mechanism (like GenStage) to offload the network work.If your backend fails to send a message to Slack, you might be tempted to log an error: Logger.error("Slack failed").
Logger inside a Logger backend. Use IO.puts or simply ignore the error.Slack has strict API rate limits. If your application crashes and generates 1,000 error logs in 10 seconds, you will be banned by Slack.
GenServer or Queue). Have the GenServer drain the queue slowly (e.g., sending 1 batch per second) to Slack.Slack messages have a character limit (roughly 4,000 chars). If you try to log a massive Elixir struct or a long stacktrace, the API will reject it.
String.slice/3 or Logger.Utils.truncate/2 on the message string before putting it into the JSON payload.