defmodule SaltLog do @moduledoc """ Module dedicated to providing effective logging into our Salt Microservices. Provides an integration into Timber.io for a better, managed experience of logs. """ @moduledoc since: "0.1.0" require Logger @log_adapter Application.get_env(:salt_log, SaltLog)[:adapter] @typedoc """ Name of the context the Logs can be searched at. """ @type context_name :: String.t() @typedoc """ Data to store the context """ @type context_data :: map() @typedoc """ All context data stored """ @type all_contexts_data :: map() @doc """ Gets the context from the supported modules of the package. Currently this is Timber. """ @callback get_context() :: all_contexts_data @doc """ Adds additional context data to the Logging Library we use """ @callback add_context(context_name, context_data) :: :ok | :error @doc """ Adds the user's ID to the context to identify their actions ## Parameters - user_id: User's UUID in platform ## Examples iex> user_id = "c5300395-11c0-45c8-8a05-b02058d79a04" iex> SaltLog.user_context(user_id) :ok """ def user_context(user_id) do @log_adapter.add_context(:user, %{id: user_id}) end @doc """ Adds context the action being completed ## Parameters - name: Name of the action - target_type: An atom describing the context in which is taking action - target_id: An id for the action to be linked to - extra: An optional map with extra action context info ## Examples iex> SaltLog.action_context(:claim_lead_merchant, :lead_merchant, merchant_id) :ok """ def action_context(name, target_type, target_id, extra \\ %{}) when is_map(extra) do action = %{ name: name, target_type: target_type, target_id: target_id } new_action = if map_size(extra) != 0, do: Map.put(action, :extra, extra), else: action @log_adapter.add_context(:action, new_action) end @doc """ Adds additional context to actions ## Parameters - extra: Extra values in Map ## Examples iex> extra = %{test: "test"} iex> SaltLog.action_context_add(extra) :ok """ def action_context_add(extra) when is_map(extra) do current_context = @log_adapter.get_context() if Map.has_key?(current_context, :action) do action = Map.get(current_context, :action) new_extra = if Map.has_key?(action, :extra) and is_map(action.extra) do action.extra |> Map.merge(extra) else extra end action_context(action.name, action.target_type, action.target_id, new_extra) end end @doc """ Adds info to the logs to further inform events that are occurring ## Parameters - message: Text to be added to the log ## Examples iex> SaltLog.info("Test message") :ok """ def info(message) do Logger.info(message) end @doc """ Adds an error to the logs ## Parameters - message: Error text to be added to the log ## Examples iex> SaltLog.error("Test error message") :ok """ def error(message) do Logger.error(message) end end