-
Notifications
You must be signed in to change notification settings - Fork 1
/
bark.ex
71 lines (56 loc) · 2.2 KB
/
bark.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
defmodule Bark do
require Logger
# Logs a list of kv pairs
@spec warn(any(), Keyword.t()) :: any()
def warn(env, opts), do: Logger.warn(fn -> parse_message(env, opts) end)
@spec info(any(), Keyword.t()) :: any()
def info(env, opts), do: Logger.info(fn -> parse_message(env, opts) end)
@spec error(any(), Keyword.t()) :: any()
def error(env, opts), do: Logger.error(fn -> parse_message(env, opts) end)
@spec debug(any(), Keyword.t()) :: any()
def debug(env, opts), do: Logger.debug(fn -> parse_message(env, opts) end)
defp parse_message(env, opts) when is_list(opts) do
env
|> add_caller_context(opts)
|> to_log_formatted_string()
end
defp to_log_formatted_string(keywords) do
keywords
|> Enum.map(fn {key, value} ->
"#{Atom.to_string(key)}=#{log_value(value)}"
end)
|> Enum.join(" ")
end
defp add_caller_context(env, opts) when is_list(opts) do
opts
|> Keyword.put_new(:line, line_number(env))
|> Keyword.put_new(:command, function_name_arity(env))
|> Keyword.put_new(:module, module(env))
end
defp module(%{:module => module} = _env) when is_atom(module) do
module
|> Atom.to_string()
|> String.replace("Elixir.", "")
end
defp module(_), do: "None"
defp function_name_arity(%{:function => {function_name, arity}}),
do: "#{function_name}/#{arity}"
defp function_name_arity(_), do: "None"
defp line_number(%{line: line}), do: line
defp line_number(not_line), do: inspect(not_line)
# Quote string if it contains a space, and if there are quotes within in the string replace them with something that
# doesn't break the parser.
defp quote_if_spaces(value) when is_binary(value) do
if String.contains?(value, " ") do
value_with_escaped_quotes = String.replace(value, "\"", "″")
"\"#{value_with_escaped_quotes}\""
else
value
end
end
# A safeguard if for some reason inspect doesn't return a binary we dont crash trying to log it.
defp quote_if_spaces(_unexpected), do: ""
defp log_value(value) when is_binary(value), do: quote_if_spaces(value)
defp log_value(value) when is_atom(value), do: Atom.to_string(value)
defp log_value(value), do: quote_if_spaces(inspect(value))
end