Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Upcoming

- allow overriding the number of decimals in float representation (`config :logster, Logster.Formatters.String, decimals: 5`)

# 2.0.0-rc.3

- `extra_fields` configuration to optionally enable `host` and `query_params` params being logged.
Expand Down
16 changes: 15 additions & 1 deletion lib/logster/formatters/string.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,21 @@ defmodule Logster.Formatters.String do
defp format_field(value), do: value

defp format_value(value) when is_binary(value), do: value
defp format_value(value) when is_float(value), do: :erlang.float_to_binary(value, decimals: 3)

defp format_value(value) when is_float(value) do
config =
Application.get_env(:logster, __MODULE__) || []

opts =
if decimals = Keyword.get(config, :decimals, 3) do
[decimals: decimals]
else
[:short]
end

:erlang.float_to_binary(value, opts)
end

defp format_value(value) when is_atom(value) or is_integer(value), do: to_string(value)

defp format_value(value) when is_map(value) do
Expand Down
20 changes: 20 additions & 0 deletions test/logster/formatters/string_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,26 @@ defmodule Logster.Formatters.StringTest do
assert result == ~s(one=two foo=bar baz=123456 qux=123.457 xyz={"fi":"fo"} zzz={"one", "two"})
end

test "can override the number of decimals for a string" do
old = Application.get_env(:logster, @formatter) || []

on_exit(fn ->
Application.put_env(:logster, @formatter, old)
end)

log = [bar: 123.4567]

Application.put_env(:logster, @formatter, Keyword.put(old, :decimals, 1))

result = log |> @formatter.format() |> IO.iodata_to_binary()
assert result == ~s(bar=123.5)

Application.put_env(:logster, @formatter, Keyword.put(old, :decimals, nil))

result = log |> @formatter.format() |> IO.iodata_to_binary()
assert result == ~s(bar=123.4567)
end

test "formats field with a non-json convertible map" do
result =
[
Expand Down