Skip to content

Instantly share code, notes, and snippets.

@adamkittelson
Created August 4, 2015 21:56
Show Gist options
  • Save adamkittelson/7fbfdaa28b03cb560e98 to your computer and use it in GitHub Desktop.
Save adamkittelson/7fbfdaa28b03cb560e98 to your computer and use it in GitHub Desktop.
Sumologic Logger Backend
use Mix.Config
...
config :logger,
backends: [:console, YourApp.SumoLogger],
level: :info,
utc_log: true
...
defmodule YourApp.SumoLogger do
use GenEvent
def init(_) do
{:ok, socket} = :gen_udp.open(0)
{:ok, configure(socket, [])}
end
def handle_call({:configure, options}, state) do
{:ok, :ok, configure(state.socket, options)}
end
def handle_event({_level, gl, _event}, state) when node(gl) != node() do
{:ok, state}
end
def handle_event({level, _gl, {Logger, msg, ts, md}}, %{level: min_level} = state) do
if is_nil(min_level) or Logger.compare_levels(level, min_level) != :lt do
log_event(level, msg, ts, md, state)
end
{:ok, state}
end
def terminate(_reason, state) do
:gen_udp.close(state.socket)
end
## Helpers
defp configure(socket, options) do
env = Application.get_env(:logger, :sumo, [])
sumo = configure_merge(env, options)
Application.put_env(:logger, :sumo, sumo)
format = sumo
|> Keyword.get(:format)
|> Logger.Formatter.compile
level = Keyword.get(sumo, :level)
metadata = Keyword.get(sumo, :metadata, [])
host = if host = System.get_env("SUMO_PORT_514_UDP_ADDR"), do: String.to_char_list(host), else: 'localhost'
port = if port = System.get_env("SUMO_PORT_514_UDP_PORT"), do: String.to_integer(port), else: 1514
%{format: format, metadata: metadata, level: level, host: host, port: port, socket: socket}
end
defp configure_merge(env, options) do
Keyword.merge(env, options, fn
_, _v1, v2 -> v2
end)
end
defp log_event(level, msg, ts, md, state) do
event = format_event(level, msg, ts, md, state)
:ok = :gen_udp.send(state.socket,
state.host,
state.port,
IO.chardata_to_string(event))
end
defp format_event(level, msg, ts, md, %{format: format, metadata: metadata}) do
Logger.Formatter.format(format, level, msg, ts, Dict.take(md, metadata))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment