logger.hrl 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2018-2022 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -ifndef(EMQX_LOGGER_HRL).
  17. -define(EMQX_LOGGER_HRL, true).
  18. %% structured logging
  19. -define(SLOG(Level, Data),
  20. ?SLOG(Level, Data, #{})
  21. ).
  22. %% structured logging, meta is for handler's filter.
  23. -define(SLOG(Level, Data, Meta),
  24. %% check 'allow' here, only evaluate Data and Meta when necessary
  25. case logger:allow(Level, ?MODULE) of
  26. true ->
  27. logger:log(
  28. Level,
  29. (Data),
  30. (Meta#{
  31. mfa => {?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY},
  32. line => ?LINE
  33. })
  34. );
  35. false ->
  36. ok
  37. end
  38. ).
  39. -define(TRACE_FILTER, emqx_trace_filter).
  40. -define(TRACE(Tag, Msg, Meta), ?TRACE(debug, Tag, Msg, Meta)).
  41. %% Only evaluate when necessary
  42. -define(TRACE(Level, Tag, Msg, Meta), begin
  43. case persistent_term:get(?TRACE_FILTER, []) of
  44. [] -> ok;
  45. %% We can't bind filter list to a variablebecause we pollute the calling scope with it.
  46. %% We also don't want to wrap the macro body in a fun
  47. %% beacause this adds overhead to the happy path.
  48. %% So evaluate `persistent_term:get` twice.
  49. _ -> emqx_trace:log(persistent_term:get(?TRACE_FILTER, []), Msg, (Meta)#{trace_tag => Tag})
  50. end,
  51. ?SLOG(
  52. Level,
  53. (emqx_trace_formatter:format_meta_map(Meta))#{msg => Msg, tag => Tag},
  54. #{is_trace => false}
  55. )
  56. end).
  57. %% print to 'user' group leader
  58. -define(ULOG(Fmt, Args), io:format(user, Fmt, Args)).
  59. -define(ELOG(Fmt, Args), io:format(standard_error, Fmt, Args)).
  60. -endif.