summaryrefslogblamecommitdiff
path: root/lib/lsg_irc/logger_plugin.ex
blob: 667f714ed484deb42369d121e660efa1a6b7d7dc (plain) (tree)



























































                                                                                          
defmodule LSG.IRC.LoggerPlugin do
  require Logger

  @couch_db "bot-logs"

  def irc_doc(), do: nil

  def start_link() do
    GenServer.start_link(__MODULE__, [], name: __MODULE__)
  end

  def init([]) do
    regopts = [plugin: __MODULE__]
    {:ok, _} = Registry.register(IRC.PubSub, "triggers", regopts)
    {:ok, _} = Registry.register(IRC.PubSub, "messages", regopts)
    {:ok, nil}
  end

  def handle_info({:irc, :trigger, _, m}, state) do
    {:noreply, log(m, state)}
  end

  def handle_info({:irc, :text, m}, state) do
    {:noreply, log(m, state)}
  end

  def handle_info(info, state) do
    Logger.debug("logger_plugin: unhandled info: #{info}")
    {:noreply, state}
  end

  def log(entry, state) do
    case Couch.post(@couch_db, format_to_db(entry)) do
      {:ok, id, _rev} ->
        Logger.debug("logger_plugin: saved: #{inspect id}")
        state
      error ->
        Logger.error("logger_plugin: save failed: #{inspect error}")
    end
  rescue
    e ->
      Logger.error("logger_plugin: rescued processing for #{inspect entry}: #{inspect e}")
      Logger.error(Exception.format(:error, e, __STACKTRACE__))
      state
  catch
    e, b ->
      Logger.error("logger_plugin: catched processing for #{inspect entry}: #{inspect e}")
      Logger.error(Exception.format(e, b, __STACKTRACE__))
      state
  end

  def format_to_db(m = %IRC.Message{}) do
    %IRC.Message{m | replyfun: nil}
  end

  def format_to_db(anything) do
    anything
  end

end