From afdda107af07a08b1d2b6c069df73d36697d4230 Mon Sep 17 00:00:00 2001 From: "Zaiming (Stone) Shi" Date: Wed, 27 Sep 2023 23:38:55 +0200 Subject: [PATCH] fix(logger): json format log encode binary list as string array --- apps/emqx/src/emqx_logger_jsonfmt.erl | 29 +++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/apps/emqx/src/emqx_logger_jsonfmt.erl b/apps/emqx/src/emqx_logger_jsonfmt.erl index cb867793e..0f04ee28c 100644 --- a/apps/emqx/src/emqx_logger_jsonfmt.erl +++ b/apps/emqx/src/emqx_logger_jsonfmt.erl @@ -235,12 +235,18 @@ json(B, Config) when is_binary(B) -> json(M, Config) when is_list(M), is_tuple(hd(M)), tuple_size(hd(M)) =:= 2 -> best_effort_json_obj(M, Config); json(L, Config) when is_list(L) -> - try unicode:characters_to_binary(L, utf8) of - B when is_binary(B) -> B; - _ -> [json(I, Config) || I <- L] - catch - _:_ -> - [json(I, Config) || I <- L] + case lists:all(fun erlang:is_binary/1, L) of + true -> + %% string array + L; + false -> + try unicode:characters_to_binary(L, utf8) of + B when is_binary(B) -> B; + _ -> [json(I, Config) || I <- L] + catch + _:_ -> + [json(I, Config) || I <- L] + end end; json(Map, Config) when is_map(Map) -> best_effort_json_obj(Map, Config); @@ -458,4 +464,15 @@ chars_limit_applied_on_format_result_test() -> ?assertEqual(Limit, size(LongStr1)), ok. +string_array_test() -> + Array = #{<<"arr">> => [<<"a">>, <<"b">>]}, + Encoded = emqx_utils_json:encode(json(Array, config())), + ?assertEqual(Array, emqx_utils_json:decode(Encoded)). + +iolist_test() -> + Iolist = #{iolist => ["a", ["b"]]}, + Concat = #{<<"iolist">> => <<"ab">>}, + Encoded = emqx_utils_json:encode(json(Iolist, config())), + ?assertEqual(Concat, emqx_utils_json:decode(Encoded)). + -endif.