Skip to content

Commit

Permalink
Handle binaries with strings, control chars, and binary data
Browse files Browse the repository at this point in the history
  • Loading branch information
reachfh committed Dec 26, 2023
1 parent ee2d510 commit 96d8ead
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/logger_formatter_json.erl
Original file line number Diff line number Diff line change
Expand Up @@ -174,10 +174,10 @@ to_string(X, Config) when is_list(X) ->
to_string(<<>>, _Config) -> <<>>;

to_string(X, Config) when is_binary(X) ->
case re:run(X, <<"[:print]+">>, [{capture, none}, unicode]) of
match -> X;
_ -> io_lib:format(p(Config), [X])
end;
case re:run(X, <<"[[:^print:]]">>, [{capture, none}, unicode]) of
match -> io_lib:format(p(Config), [X]);
_ -> X
end;

to_string(X, Config) -> io_lib:format(p(Config), [X]).

Expand Down
51 changes: 51 additions & 0 deletions test/logger_formatter_json_SUITE.erl
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,57 @@ unstructured(_) ->
)
)
),
?assertEqual(
<<"{\"msg\":\"hello world\",\"level\":\"info\",\"request_id\":\"F6R64Fh3F9NzEscAAAaB\"}\n">>,
iolist_to_binary(
logger_formatter_json:format(
#{
level => info,
msg => {"hello ~s", ["world"]},
meta => #{request_id => <<"F6R64Fh3F9NzEscAAAaB">>}
},
#{}
)
)
),
?assertEqual(
<<"{\"msg\":\"hello world\",\"level\":\"info\",\"request_id\":\"string with spaces\"}\n">>,
iolist_to_binary(
logger_formatter_json:format(
#{
level => info,
msg => {"hello ~s", ["world"]},
meta => #{request_id => <<"string with spaces">>}
},
#{}
)
)
),
?assertEqual(
<<
"{\"msg\":\"hello world\",\"level\":\"info\",\"foo\":\"<<\\\"string with control char\\\\n\\\">>\"}\n"
>>,
iolist_to_binary(
logger_formatter_json:format(
#{
level => info,
msg => {"hello ~s", ["world"]},
meta => #{foo => <<"string with control char\n">>}
},
#{}
)
)
),
% Binary data
?assertEqual(
<<"{\"msg\":\"hello world\",\"level\":\"info\",\"foo\":\"<<0,1,2,3>>\"}\n">>,
iolist_to_binary(
logger_formatter_json:format(
#{level => info, msg => {"hello ~s", ["world"]}, meta => #{foo => <<0, 1, 2, 3>>}},
#{}
)
)
),
ok.


Expand Down

0 comments on commit 96d8ead

Please sign in to comment.