Skip to content

Instantly share code, notes, and snippets.

@sofakingworld
Last active February 14, 2018 09:17
Show Gist options
  • Save sofakingworld/f1ef63b3ef4ae3391727d9b47a950441 to your computer and use it in GitHub Desktop.
Save sofakingworld/f1ef63b3ef4ae3391727d9b47a950441 to your computer and use it in GitHub Desktop.
Форматирование логов
.....
config :logger, :console,
level: :debug,
format: {LoggerFormatter, :format_log},
defmodule LoggerFormatter do
@moduledoc false
@doc """
function formats logger message
"""
def format_log(level, message, timestamp, metadata) do
[module_name, {:pid, pid}] = metadata
"#{timestamp_to_string(timestamp)} [#{inspect pid}] [#{level}] #{message_to_string_with_limit(message)}\n"
end
@doc """
by default string's length = 1500 symbols
if string is lonпer, then after 1500 symbols adds "... (total length 3218)"
"""
def message_to_string_with_limit(message, length \\ 1500) do
str_msg = to_string message
additional_text = case String.length(str_msg) > length do
:true -> "... (total length #{String.length(str_msg)})"
:false -> ""
end
str_msg = String.replace(str_msg, "\n", "\\n")
String.slice(str_msg, 0..length) <> additional_text
end
@doc """
transforms logger timestamps to string
"""
def timestamp_to_string(timestamp) do
{date_tuple, time_tuple_wth_ms} = timestamp
"#{format_date(date_tuple)} #{format_time(time_tuple_wth_ms)}"
end
# logger's default functions
defp pad2(int) when int < 10, do: [?0, Integer.to_string(int)]
defp pad2(int), do: Integer.to_string(int)
defp pad3(int) when int < 10, do: [?0, ?0, Integer.to_string(int)]
defp pad3(int) when int < 100, do: [?0, Integer.to_string(int)]
defp pad3(int), do: Integer.to_string(int)
def format_date({yy, mm, dd}) do
[Integer.to_string(yy), ?-, pad2(mm), ?-, pad2(dd)]
end
def format_time({hh, mi, ss, ms}) do
[pad2(hh), ?:, pad2(mi), ?:, pad2(ss), ?., pad3(ms)]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment