rewrite from lager
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

1917 řádky
86 KiB

před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
  1. %% -------------------------------------------------------------------
  2. %%
  3. %% Copyright (c) 2011-2017 Basho Technologies, Inc.
  4. %%
  5. %% This file is provided to you under the Apache License,
  6. %% Version 2.0 (the "License"); you may not use this file
  7. %% except in compliance with the License. You may obtain
  8. %% a copy of the License at
  9. %%
  10. %% http://www.apache.org/licenses/LICENSE-2.0
  11. %%
  12. %% Unless required by applicable law or agreed to in writing,
  13. %% software distributed under the License is distributed on an
  14. %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. %% KIND, either express or implied. See the License for the
  16. %% specific language governing permissions and limitations
  17. %% under the License.
  18. %%
  19. %% -------------------------------------------------------------------
  20. -module(lager_test_backend).
  21. -behaviour(gen_event).
  22. -export([init/1, handle_call/2, handle_event/2, handle_info/2, terminate/2,
  23. code_change/3]).
  24. -include("rum.hrl").
  25. -define(TEST_SINK_NAME, '__lager_test_sink'). %% <-- used by parse transform
  26. -define(TEST_SINK_EVENT, '__lager_test_sink_lager_event'). %% <-- used by lager API calls and internals for gen_event
  27. -record(state, {
  28. level :: list(),
  29. buffer :: list(),
  30. ignored :: term()
  31. }).
  32. -compile({parse_transform, lager_transform}).
  33. -ifdef(TEST).
  34. -include_lib("eunit/include/eunit.hrl").
  35. -record(test, {
  36. attrs :: list(),
  37. format :: list(),
  38. args :: list()
  39. }).
  40. -export([
  41. count/0,
  42. count_ignored/0,
  43. flush/0,
  44. message_stuffer/3,
  45. pop/0,
  46. pop_ignored/0,
  47. print_state/0,
  48. get_buffer/0
  49. ]).
  50. -endif.
  51. init(Level) ->
  52. {ok, #state{level = rumUtil:config_to_mask(Level), buffer = [], ignored = []}}.
  53. handle_call(count, #state{buffer = Buffer} = State) ->
  54. {ok, length(Buffer), State};
  55. handle_call(count_ignored, #state{ignored = Ignored} = State) ->
  56. {ok, length(Ignored), State};
  57. handle_call(flush, State) ->
  58. {ok, ok, State#state{buffer = [], ignored = []}};
  59. handle_call(pop, #state{buffer = Buffer} = State) ->
  60. case Buffer of
  61. [] ->
  62. {ok, undefined, State};
  63. [H | T] ->
  64. {ok, H, State#state{buffer = T}}
  65. end;
  66. handle_call(pop_ignored, #state{ignored = Ignored} = State) ->
  67. case Ignored of
  68. [] ->
  69. {ok, undefined, State};
  70. [H | T] ->
  71. {ok, H, State#state{ignored = T}}
  72. end;
  73. handle_call(get_buffer, #state{buffer = Buffer} = State) ->
  74. {ok, Buffer, State};
  75. handle_call(get_loglevel, #state{level = Level} = State) ->
  76. {ok, Level, State};
  77. handle_call({set_loglevel, Level}, State) ->
  78. {ok, ok, State#state{level = rumUtil:config_to_mask(Level)}};
  79. handle_call(print_state, State) ->
  80. spawn(fun() -> eRum:info("State ~p", [eRum:pr(State, ?MODULE)]) end),
  81. timer:sleep(100),
  82. {ok, ok, State};
  83. handle_call(print_bad_state, State) ->
  84. spawn(fun() -> eRum:info("State ~p", [eRum:pr({state, 1}, ?MODULE)]) end),
  85. timer:sleep(100),
  86. {ok, ok, State};
  87. handle_call(_Request, State) ->
  88. {ok, ok, State}.
  89. handle_event({log, Msg},
  90. #state{level = LogLevel, buffer = Buffer, ignored = Ignored} = State) ->
  91. case rumUtil:is_loggable(Msg, LogLevel, ?MODULE) of
  92. true ->
  93. {ok, State#state{buffer = Buffer ++
  94. [{lager_msg:severity_as_int(Msg),
  95. lager_msg:datetime(Msg),
  96. lager_msg:message(Msg), lager_msg:metadata(Msg)}]}};
  97. _ ->
  98. {ok, State#state{ignored = Ignored ++ [Msg]}}
  99. end;
  100. handle_event(_Event, State) ->
  101. {ok, State}.
  102. handle_info(_Info, State) ->
  103. {ok, State}.
  104. terminate(_Reason, _State) ->
  105. ok.
  106. code_change(_OldVsn, State, _Extra) ->
  107. {ok, State}.
  108. -ifdef(TEST).
  109. pop() ->
  110. pop(lager_event).
  111. pop_ignored() ->
  112. pop_ignored(lager_event).
  113. get_buffer() ->
  114. get_buffer(lager_event).
  115. count() ->
  116. count(lager_event).
  117. count_ignored() ->
  118. count_ignored(lager_event).
  119. flush() ->
  120. flush(lager_event).
  121. print_state() ->
  122. print_state(lager_event).
  123. print_bad_state() ->
  124. print_bad_state(lager_event).
  125. pop(Sink) ->
  126. gen_event:call(Sink, ?MODULE, pop).
  127. pop_ignored(Sink) ->
  128. gen_event:call(Sink, ?MODULE, pop_ignored).
  129. get_buffer(Sink) ->
  130. gen_event:call(Sink, ?MODULE, get_buffer).
  131. count(Sink) ->
  132. gen_event:call(Sink, ?MODULE, count).
  133. count_ignored(Sink) ->
  134. gen_event:call(Sink, ?MODULE, count_ignored).
  135. flush(Sink) ->
  136. gen_event:call(Sink, ?MODULE, flush).
  137. print_state(Sink) ->
  138. gen_event:call(Sink, ?MODULE, print_state).
  139. print_bad_state(Sink) ->
  140. gen_event:call(Sink, ?MODULE, print_bad_state).
  141. not_running_test() ->
  142. ?assertEqual({error, lager_not_running}, eRum:log(info, self(), "not running")).
  143. lager_test_() ->
  144. {foreach,
  145. fun setup/0,
  146. fun cleanup/1,
  147. [
  148. {"observe that there is nothing up my sleeve",
  149. fun() ->
  150. ?assertEqual(undefined, pop()),
  151. ?assertEqual(0, count())
  152. end
  153. },
  154. {"test sink not running",
  155. fun() ->
  156. ?assertEqual({error, {sink_not_configured, test}}, eRum:log(test, info, self(), "~p", "not running"))
  157. end
  158. },
  159. {"logging works",
  160. fun() ->
  161. eRum:warning("test message"),
  162. ?assertEqual(1, count()),
  163. {Level, _Time, Message, _Metadata} = pop(),
  164. ?assertMatch(Level, rumUtil:level_to_num(warning)),
  165. ?assertEqual("test message", Message),
  166. ok
  167. end
  168. },
  169. {"logging with macro works",
  170. fun() ->
  171. ?rumWarning("test message", []),
  172. ?assertEqual(1, count()),
  173. {Level, _Time, Message, _Metadata} = pop(),
  174. ?assertMatch(Level, rumUtil:level_to_num(warning)),
  175. ?assertEqual("test message", Message),
  176. ok
  177. end
  178. },
  179. {"unsafe logging works",
  180. fun() ->
  181. eRum:warning_unsafe("test message"),
  182. ?assertEqual(1, count()),
  183. {Level, _Time, Message, _Metadata} = pop(),
  184. ?assertMatch(Level, rumUtil:level_to_num(warning)),
  185. ?assertEqual("test message", Message),
  186. ok
  187. end
  188. },
  189. {"logging with arguments works",
  190. fun() ->
  191. eRum:warning("test message ~p", [self()]),
  192. ?assertEqual(1, count()),
  193. {Level, _Time, Message, _Metadata} = pop(),
  194. ?assertMatch(Level, rumUtil:level_to_num(warning)),
  195. ?assertEqual(lists:flatten(io_lib:format("test message ~p", [self()])), lists:flatten(Message)),
  196. ok
  197. end
  198. },
  199. {"logging with macro and arguments works",
  200. fun() ->
  201. ?rumWarning("test message ~p", [self()]),
  202. ?assertEqual(1, count()),
  203. {Level, _Time, Message, _Metadata} = pop(),
  204. ?assertMatch(Level, rumUtil:level_to_num(warning)),
  205. ?assertEqual(lists:flatten(io_lib:format("test message ~p", [self()])), lists:flatten(Message)),
  206. ok
  207. end
  208. },
  209. {"unsafe logging with args works",
  210. fun() ->
  211. eRum:warning_unsafe("test message ~p", [self()]),
  212. ?assertEqual(1, count()),
  213. {Level, _Time, Message, _Metadata} = pop(),
  214. ?assertMatch(Level, rumUtil:level_to_num(warning)),
  215. ?assertEqual(lists:flatten(io_lib:format("test message ~p", [self()])), lists:flatten(Message)),
  216. ok
  217. end
  218. },
  219. {"logging works from inside a begin/end block",
  220. fun() ->
  221. ?assertEqual(0, count()),
  222. begin
  223. eRum:warning("test message 2")
  224. end,
  225. ?assertEqual(1, count()),
  226. ok
  227. end
  228. },
  229. {"logging works from inside a list comprehension",
  230. fun() ->
  231. ?assertEqual(0, count()),
  232. [eRum:warning("test message") || _N <- lists:seq(1, 10)],
  233. ?assertEqual(10, count()),
  234. ok
  235. end
  236. },
  237. {"logging works from a begin/end block inside a list comprehension",
  238. fun() ->
  239. ?assertEqual(0, count()),
  240. [begin eRum:warning("test message") end || _N <- lists:seq(1, 10)],
  241. ?assertEqual(10, count()),
  242. ok
  243. end
  244. },
  245. {"logging works from a nested list comprehension",
  246. fun() ->
  247. ?assertEqual(0, count()),
  248. [[eRum:warning("test message") || _N <- lists:seq(1, 10)] ||
  249. _I <- lists:seq(1, 10)],
  250. ?assertEqual(100, count()),
  251. ok
  252. end
  253. },
  254. {"logging with only metadata works",
  255. fun() ->
  256. ?assertEqual(0, count()),
  257. eRum:warning([{just, metadata}]),
  258. eRum:warning([{just, metadata}, {foo, bar}]),
  259. ?assertEqual(2, count()),
  260. ok
  261. end
  262. },
  263. {"variables inplace of literals in logging statements work",
  264. fun() ->
  265. ?assertEqual(0, count()),
  266. Attr = [{a, alpha}, {b, beta}],
  267. Fmt = "format ~p",
  268. Args = [world],
  269. eRum:info(Attr, "hello"),
  270. eRum:info(Attr, "hello ~p", [world]),
  271. eRum:info(Fmt, [world]),
  272. eRum:info("hello ~p", Args),
  273. eRum:info(Attr, "hello ~p", Args),
  274. eRum:info([{d, delta}, {g, gamma}], Fmt, Args),
  275. ?assertEqual(6, count()),
  276. {_Level, _Time, Message, Metadata} = pop(),
  277. ?assertMatch([{a, alpha}, {b, beta} | _], Metadata),
  278. ?assertEqual("hello", lists:flatten(Message)),
  279. {_Level, _Time2, Message2, _Metadata2} = pop(),
  280. ?assertEqual("hello world", lists:flatten(Message2)),
  281. {_Level, _Time3, Message3, _Metadata3} = pop(),
  282. ?assertEqual("format world", lists:flatten(Message3)),
  283. {_Level, _Time4, Message4, _Metadata4} = pop(),
  284. ?assertEqual("hello world", lists:flatten(Message4)),
  285. {_Level, _Time5, Message5, _Metadata5} = pop(),
  286. ?assertEqual("hello world", lists:flatten(Message5)),
  287. {_Level, _Time6, Message6, Metadata6} = pop(),
  288. ?assertMatch([{d, delta}, {g, gamma} | _], Metadata6),
  289. ?assertEqual("format world", lists:flatten(Message6)),
  290. ok
  291. end
  292. },
  293. {"list comprehension inplace of literals in logging statements work",
  294. fun() ->
  295. ?assertEqual(0, count()),
  296. Attr = [{a, alpha}, {b, beta}],
  297. Fmt = "format ~p",
  298. Args = [world],
  299. eRum:info([{K, atom_to_list(V)} || {K, V} <- Attr], "hello"),
  300. eRum:info([{K, atom_to_list(V)} || {K, V} <- Attr], "hello ~p", [{atom, X} || X <- Args]),
  301. eRum:info([X || X <- Fmt], [world]),
  302. eRum:info("hello ~p", [{atom, X} || X <- Args]),
  303. eRum:info([{K, atom_to_list(V)} || {K, V} <- Attr], "hello ~p", [{atom, X} || X <- Args]),
  304. eRum:info([{d, delta}, {g, gamma}], Fmt, [{atom, X} || X <- Args]),
  305. ?assertEqual(6, count()),
  306. {_Level, _Time, Message, Metadata} = pop(),
  307. ?assertMatch([{a, "alpha"}, {b, "beta"} | _], Metadata),
  308. ?assertEqual("hello", lists:flatten(Message)),
  309. {_Level, _Time2, Message2, _Metadata2} = pop(),
  310. ?assertEqual("hello {atom,world}", lists:flatten(Message2)),
  311. {_Level, _Time3, Message3, _Metadata3} = pop(),
  312. ?assertEqual("format world", lists:flatten(Message3)),
  313. {_Level, _Time4, Message4, _Metadata4} = pop(),
  314. ?assertEqual("hello {atom,world}", lists:flatten(Message4)),
  315. {_Level, _Time5, Message5, _Metadata5} = pop(),
  316. ?assertEqual("hello {atom,world}", lists:flatten(Message5)),
  317. {_Level, _Time6, Message6, Metadata6} = pop(),
  318. ?assertMatch([{d, delta}, {g, gamma} | _], Metadata6),
  319. ?assertEqual("format {atom,world}", lists:flatten(Message6)),
  320. ok
  321. end
  322. },
  323. {"function calls inplace of literals in logging statements work",
  324. fun() ->
  325. ?assertEqual(0, count()),
  326. put(attrs, [{a, alpha}, {b, beta}]),
  327. put(format, "format ~p"),
  328. put(args, [world]),
  329. eRum:info(get(attrs), "hello"),
  330. eRum:info(get(attrs), "hello ~p", get(args)),
  331. eRum:info(get(format), [world]),
  332. eRum:info("hello ~p", erlang:get(args)),
  333. eRum:info(fun() -> get(attrs) end(), "hello ~p", get(args)),
  334. eRum:info([{d, delta}, {g, gamma}], get(format), get(args)),
  335. ?assertEqual(6, count()),
  336. {_Level, _Time, Message, Metadata} = pop(),
  337. ?assertMatch([{a, alpha}, {b, beta} | _], Metadata),
  338. ?assertEqual("hello", lists:flatten(Message)),
  339. {_Level, _Time2, Message2, _Metadata2} = pop(),
  340. ?assertEqual("hello world", lists:flatten(Message2)),
  341. {_Level, _Time3, Message3, _Metadata3} = pop(),
  342. ?assertEqual("format world", lists:flatten(Message3)),
  343. {_Level, _Time4, Message4, _Metadata4} = pop(),
  344. ?assertEqual("hello world", lists:flatten(Message4)),
  345. {_Level, _Time5, Message5, _Metadata5} = pop(),
  346. ?assertEqual("hello world", lists:flatten(Message5)),
  347. {_Level, _Time6, Message6, Metadata6} = pop(),
  348. ?assertMatch([{d, delta}, {g, gamma} | _], Metadata6),
  349. ?assertEqual("format world", lists:flatten(Message6)),
  350. ok
  351. end
  352. },
  353. {"record fields inplace of literals in logging statements work",
  354. fun() ->
  355. ?assertEqual(0, count()),
  356. Test = #test{attrs = [{a, alpha}, {b, beta}], format = "format ~p", args = [world]},
  357. eRum:info(Test#test.attrs, "hello"),
  358. eRum:info(Test#test.attrs, "hello ~p", Test#test.args),
  359. eRum:info(Test#test.format, [world]),
  360. eRum:info("hello ~p", Test#test.args),
  361. eRum:info(Test#test.attrs, "hello ~p", Test#test.args),
  362. eRum:info([{d, delta}, {g, gamma}], Test#test.format, Test#test.args),
  363. ?assertEqual(6, count()),
  364. {_Level, _Time, Message, Metadata} = pop(),
  365. ?assertMatch([{a, alpha}, {b, beta} | _], Metadata),
  366. ?assertEqual("hello", lists:flatten(Message)),
  367. {_Level, _Time2, Message2, _Metadata2} = pop(),
  368. ?assertEqual("hello world", lists:flatten(Message2)),
  369. {_Level, _Time3, Message3, _Metadata3} = pop(),
  370. ?assertEqual("format world", lists:flatten(Message3)),
  371. {_Level, _Time4, Message4, _Metadata4} = pop(),
  372. ?assertEqual("hello world", lists:flatten(Message4)),
  373. {_Level, _Time5, Message5, _Metadata5} = pop(),
  374. ?assertEqual("hello world", lists:flatten(Message5)),
  375. {_Level, _Time6, Message6, Metadata6} = pop(),
  376. ?assertMatch([{d, delta}, {g, gamma} | _], Metadata6),
  377. ?assertEqual("format world", lists:flatten(Message6)),
  378. ok
  379. end
  380. },
  381. {"log messages below the threshold are ignored",
  382. fun() ->
  383. ?assertEqual(0, count()),
  384. eRum:debug("this message will be ignored"),
  385. ?assertEqual(0, count()),
  386. ?assertEqual(0, count_ignored()),
  387. lager_config:set(loglevel, {element(2, rumUtil:config_to_mask(debug)), []}),
  388. eRum:debug("this message should be ignored"),
  389. ?assertEqual(0, count()),
  390. ?assertEqual(1, count_ignored()),
  391. eRum:set_loglevel(?MODULE, debug),
  392. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  393. eRum:debug("this message should be logged"),
  394. ?assertEqual(1, count()),
  395. ?assertEqual(1, count_ignored()),
  396. ?assertEqual(debug, eRum:get_loglevel(?MODULE)),
  397. ok
  398. end
  399. },
  400. {"tracing works",
  401. fun() ->
  402. lager_config:set(loglevel, {element(2, rumUtil:config_to_mask(error)), []}),
  403. ok = eRum:info("hello world"),
  404. ?assertEqual(0, count()),
  405. eRum:trace(?MODULE, [{module, ?MODULE}], debug),
  406. ?assertMatch({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, _}, lager_config:get(loglevel)),
  407. %% elegible for tracing
  408. ok = eRum:info("hello world"),
  409. %% NOT elegible for tracing
  410. ok = eRum:log(info, [{pid, self()}], "hello world"),
  411. ?assertEqual(1, count()),
  412. ok
  413. end
  414. },
  415. {"tracing works with custom attributes",
  416. fun() ->
  417. eRum:set_loglevel(?MODULE, error),
  418. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  419. lager_config:set(loglevel, {element(2, rumUtil:config_to_mask(error)), []}),
  420. eRum:info([{requestid, 6}], "hello world"),
  421. ?assertEqual(0, count()),
  422. eRum:trace(?MODULE, [{requestid, 6}, {foo, bar}], debug),
  423. eRum:info([{requestid, 6}, {foo, bar}], "hello world"),
  424. ?assertEqual(1, count()),
  425. eRum:trace(?MODULE, [{requestid, '*'}], debug),
  426. eRum:info([{requestid, 6}], "hello world"),
  427. ?assertEqual(2, count()),
  428. eRum:clear_all_traces(),
  429. eRum:info([{requestid, 6}], "hello world"),
  430. ?assertEqual(2, count()),
  431. ok
  432. end
  433. },
  434. {"tracing works with custom attributes and event stream processing",
  435. fun() ->
  436. eRum:set_loglevel(?MODULE, error),
  437. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  438. lager_config:set(loglevel, {element(2, rumUtil:config_to_mask(error)), []}),
  439. eRum:info([{requestid, 6}], "hello world"),
  440. ?assertEqual(0, count()),
  441. eRum:trace(?MODULE, [{requestid, '>', 5}, {requestid, '<', 7}, {foo, bar}], debug),
  442. eRum:info([{requestid, 5}, {foo, bar}], "hello world"),
  443. eRum:info([{requestid, 6}, {foo, bar}], "hello world"),
  444. ?assertEqual(1, count()),
  445. eRum:clear_all_traces(),
  446. eRum:trace(?MODULE, [{requestid, '>', 8}, {foo, bar}]),
  447. eRum:info([{foo, bar}], "hello world"),
  448. eRum:info([{requestid, 6}], "hello world"),
  449. eRum:info([{requestid, 7}], "hello world"),
  450. eRum:info([{requestid, 8}], "hello world"),
  451. eRum:info([{requestid, 9}, {foo, bar}], "hello world"),
  452. eRum:info([{requestid, 10}], "hello world"),
  453. ?assertEqual(2, count()),
  454. eRum:trace(?MODULE, [{requestid, '>', 8}]),
  455. eRum:info([{foo, bar}], "hello world"),
  456. eRum:info([{requestid, 6}], "hello world"),
  457. eRum:info([{requestid, 7}], "hello world"),
  458. eRum:info([{requestid, 8}], "hello world"),
  459. eRum:info([{requestid, 9}, {foo, bar}], "hello world"),
  460. eRum:info([{requestid, 10}], "hello world"),
  461. ?assertEqual(4, count()),
  462. eRum:trace(?MODULE, [{foo, '=', bar}]),
  463. eRum:info([{foo, bar}], "hello world"),
  464. eRum:info([{requestid, 6}], "hello world"),
  465. eRum:info([{requestid, 7}], "hello world"),
  466. eRum:info([{requestid, 8}], "hello world"),
  467. eRum:info([{requestid, 9}, {foo, bar}], "hello world"),
  468. eRum:info([{requestid, 10}], "hello world"),
  469. eRum:trace(?MODULE, [{fu, '!'}]),
  470. eRum:info([{foo, bar}], "hello world"),
  471. eRum:info([{ooh, car}], "hello world"),
  472. eRum:info([{fu, bar}], "hello world"),
  473. eRum:trace(?MODULE, [{fu, '*'}]),
  474. eRum:info([{fu, bar}], "hello world"),
  475. ?assertEqual(10, count()),
  476. eRum:clear_all_traces(),
  477. eRum:info([{requestid, 6}], "hello world"),
  478. ?assertEqual(10, count()),
  479. eRum:clear_all_traces(),
  480. eRum:trace(?MODULE, [{requestid, '>=', 5}, {requestid, '=<', 7}], debug),
  481. eRum:info([{requestid, 4}], "nope!"),
  482. eRum:info([{requestid, 5}], "hello world"),
  483. eRum:info([{requestid, 7}], "hello world again"),
  484. ?assertEqual(12, count()),
  485. eRum:clear_all_traces(),
  486. eRum:trace(?MODULE, [{foo, '!=', bar}]),
  487. eRum:info([{foo, bar}], "hello world"),
  488. ?assertEqual(12, count()),
  489. eRum:info([{foo, baz}], "blarg"),
  490. ?assertEqual(13, count()),
  491. eRum:clear_all_traces(),
  492. eRum:trace(?MODULE, [{all, [{foo, '=', bar}, {null, false}]}]),
  493. eRum:info([{foo, bar}], "should not be logged"),
  494. ?assertEqual(13, count()),
  495. eRum:clear_all_traces(),
  496. eRum:trace(?MODULE, [{any, [{foo, '=', bar}, {null, true}]}]),
  497. eRum:info([{foo, qux}], "should be logged"),
  498. ?assertEqual(14, count()),
  499. ok
  500. end
  501. },
  502. {"tracing custom attributes works with event stream processing statistics and reductions",
  503. fun() ->
  504. eRum:set_loglevel(?MODULE, error),
  505. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  506. lager_config:set(loglevel, {element(2, rumUtil:config_to_mask(error)), []}),
  507. eRum:info([{requestid, 6}], "hello world"),
  508. ?assertEqual(0, count()),
  509. eRum:trace(?MODULE, [{beta, '*'}]),
  510. eRum:trace(?MODULE, [{meta, "data"}]),
  511. eRum:info([{meta, "data"}], "hello world"),
  512. eRum:info([{beta, 2}], "hello world"),
  513. eRum:info([{beta, 2.1}, {foo, bar}], "hello world"),
  514. eRum:info([{meta, <<"data">>}], "hello world"),
  515. ?assertEqual(8, ?RumDefTracer:info(input)),
  516. ?assertEqual(6, ?RumDefTracer:info(output)),
  517. ?assertEqual(2, ?RumDefTracer:info(filter)),
  518. eRum:clear_all_traces(),
  519. eRum:trace(?MODULE, [{meta, "data"}]),
  520. eRum:trace(?MODULE, [{beta, '>', 2}, {beta, '<', 2.12}]),
  521. eRum:info([{meta, "data"}], "hello world"),
  522. eRum:info([{beta, 2}], "hello world"),
  523. eRum:info([{beta, 2.1}, {foo, bar}], "hello world"),
  524. eRum:info([{meta, <<"data">>}], "hello world"),
  525. ?assertEqual(8, ?RumDefTracer:info(input)),
  526. ?assertEqual(4, ?RumDefTracer:info(output)),
  527. ?assertEqual(4, ?RumDefTracer:info(filter)),
  528. eRum:clear_all_traces(),
  529. eRum:trace_console([{beta, '>', 2}, {meta, "data"}]),
  530. eRum:trace_console([{beta, '>', 2}, {beta, '<', 2.12}]),
  531. Reduced = {all, [{any, [{beta, '<', 2.12}, {meta, '=', "data"}]},
  532. {beta, '>', 2}]},
  533. ?assertEqual(Reduced, ?RumDefTracer:info('query')),
  534. eRum:clear_all_traces(),
  535. eRum:info([{requestid, 6}], "hello world"),
  536. ?assertEqual(5, count()),
  537. ok
  538. end
  539. },
  540. {"persistent traces work",
  541. fun() ->
  542. ?assertEqual(0, count()),
  543. eRum:debug([{foo, bar}], "hello world"),
  544. ?assertEqual(0, count()),
  545. application:stop(lager),
  546. application:set_env(lager, traces, [{lager_test_backend, [{foo, bar}], debug}]),
  547. eRum:start(),
  548. timer:sleep(5),
  549. flush(),
  550. eRum:debug([{foo, bar}], "hello world"),
  551. ?assertEqual(1, count()),
  552. application:unset_env(lager, traces),
  553. ok
  554. end
  555. },
  556. {"tracing honors loglevel",
  557. fun() ->
  558. eRum:set_loglevel(?MODULE, error),
  559. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  560. {ok, T} = eRum:trace(?MODULE, [{module, ?MODULE}], notice),
  561. ok = eRum:info("hello world"),
  562. ?assertEqual(0, count()),
  563. ok = eRum:notice("hello world"),
  564. ?assertEqual(1, count()),
  565. eRum:stop_trace(T),
  566. ok = eRum:notice("hello world"),
  567. ?assertEqual(1, count()),
  568. ok
  569. end
  570. },
  571. {"stopped trace stops and removes its event handler - default sink (gh#267)",
  572. {timeout, 10,
  573. fun() ->
  574. Sink = ?RumDefSink,
  575. StartHandlers = gen_event:which_handlers(Sink),
  576. {_, T0} = lager_config:get({Sink, loglevel}),
  577. StartGlobal = lager_config:global_get(handlers),
  578. ?assertEqual([], T0),
  579. {ok, TestTrace1} = eRum:trace_file("/tmp/test", [{a, b}]),
  580. MidHandlers = gen_event:which_handlers(Sink),
  581. {ok, TestTrace2} = eRum:trace_file("/tmp/test", [{c, d}]),
  582. MidHandlers = gen_event:which_handlers(Sink),
  583. ?assertEqual(length(StartHandlers) + 1, length(MidHandlers)),
  584. MidGlobal = lager_config:global_get(handlers),
  585. ?assertEqual(length(StartGlobal) + 1, length(MidGlobal)),
  586. {_, T1} = lager_config:get({Sink, loglevel}),
  587. ?assertEqual(2, length(T1)),
  588. ok = eRum:stop_trace(TestTrace1),
  589. {_, T2} = lager_config:get({Sink, loglevel}),
  590. ?assertEqual(1, length(T2)),
  591. ?assertEqual(length(StartHandlers) + 1, length(
  592. gen_event:which_handlers(Sink))),
  593. ?assertEqual(length(StartGlobal) + 1, length(lager_config:global_get(handlers))),
  594. ok = eRum:stop_trace(TestTrace2),
  595. EndHandlers = gen_event:which_handlers(Sink),
  596. EndGlobal = lager_config:global_get(handlers),
  597. {_, T3} = lager_config:get({Sink, loglevel}),
  598. ?assertEqual([], T3),
  599. ?assertEqual(StartHandlers, EndHandlers),
  600. ?assertEqual(StartGlobal, EndGlobal),
  601. ok
  602. end}
  603. },
  604. {"record printing works",
  605. fun() ->
  606. print_state(),
  607. {Level, _Time, Message, _Metadata} = pop(),
  608. ?assertMatch(Level, rumUtil:level_to_num(info)),
  609. {mask, Mask} = rumUtil:config_to_mask(info),
  610. ?assertEqual("State #state{level={mask," ++ integer_to_list(Mask) ++ "},buffer=[],ignored=[]}", lists:flatten(Message)),
  611. ok
  612. end
  613. },
  614. {"record printing fails gracefully",
  615. fun() ->
  616. print_bad_state(),
  617. {Level, _Time, Message, _Metadata} = pop(),
  618. ?assertMatch(Level, rumUtil:level_to_num(info)),
  619. ?assertEqual("State {state,1}", lists:flatten(Message)),
  620. ok
  621. end
  622. },
  623. {"record printing fails gracefully when no lager_record attribute",
  624. fun() ->
  625. spawn(fun() -> eRum:info("State ~p", [eRum:pr({state, 1}, lager)]) end),
  626. timer:sleep(100),
  627. {Level, _Time, Message, _Metadata} = pop(),
  628. ?assertMatch(Level, rumUtil:level_to_num(info)),
  629. ?assertEqual("State {state,1}", lists:flatten(Message)),
  630. ok
  631. end
  632. },
  633. {"record printing fails gracefully when input is not a tuple",
  634. fun() ->
  635. spawn(fun() -> eRum:info("State ~p", [eRum:pr(ok, lager)]) end),
  636. timer:sleep(100),
  637. {Level, _Time, Message, _Metadata} = pop(),
  638. ?assertMatch(Level, rumUtil:level_to_num(info)),
  639. ?assertEqual("State ok", lists:flatten(Message)),
  640. ok
  641. end
  642. },
  643. {"record printing fails gracefully when module is invalid",
  644. fun() ->
  645. spawn(fun() -> eRum:info("State ~p", [eRum:pr({state, 1}, not_a_module)]) end),
  646. timer:sleep(1000),
  647. {Level, _Time, Message, _Metadata} = pop(),
  648. ?assertMatch(Level, rumUtil:level_to_num(info)),
  649. ?assertEqual("State {state,1}", lists:flatten(Message)),
  650. ok
  651. end
  652. },
  653. {"installing a new handler adjusts the global loglevel if necessary",
  654. fun() ->
  655. ?assertEqual({?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  656. supervisor:start_child(lager_handler_watcher_sup, [lager_event, {?MODULE, foo}, debug]),
  657. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  658. ok
  659. end
  660. },
  661. {"metadata in the process dictionary works",
  662. fun() ->
  663. eRum:md([{platypus, gravid}, {sloth, hirsute}, {duck, erroneous}]),
  664. eRum:info("I sing the animal kingdom electric!"),
  665. {_Level, _Time, _Message, Metadata} = pop(),
  666. ?assertEqual(gravid, proplists:get_value(platypus, Metadata)),
  667. ?assertEqual(hirsute, proplists:get_value(sloth, Metadata)),
  668. ?assertEqual(erroneous, proplists:get_value(duck, Metadata)),
  669. ?assertEqual(undefined, proplists:get_value(eagle, Metadata)),
  670. eRum:md([{platypus, gravid}, {sloth, hirsute}, {eagle, superincumbent}]),
  671. eRum:info("I sing the animal kingdom dielectric!"),
  672. {_Level2, _Time2, _Message2, Metadata2} = pop(),
  673. ?assertEqual(gravid, proplists:get_value(platypus, Metadata2)),
  674. ?assertEqual(hirsute, proplists:get_value(sloth, Metadata2)),
  675. ?assertEqual(undefined, proplists:get_value(duck, Metadata2)),
  676. ?assertEqual(superincumbent, proplists:get_value(eagle, Metadata2)),
  677. ok
  678. end
  679. },
  680. {"unsafe messages really are not truncated",
  681. fun() ->
  682. eRum:info_unsafe("doom, doom has come upon you all ~p", [string:copies("doom", 1500)]),
  683. {_, _, Msg, _Metadata} = pop(),
  684. ?assert(length(lists:flatten(Msg)) == 6035)
  685. end
  686. },
  687. {"can't store invalid metadata",
  688. fun() ->
  689. ?assertEqual(ok, eRum:md([{platypus, gravid}, {sloth, hirsute}, {duck, erroneous}])),
  690. ?assertError(badarg, eRum:md({flamboyant, flamingo})),
  691. ?assertError(badarg, eRum:md("zookeeper zephyr")),
  692. ok
  693. end
  694. },
  695. {"dates should be local by default",
  696. fun() ->
  697. eRum:warning("so long, and thanks for all the fish"),
  698. ?assertEqual(1, count()),
  699. {_Level, {_Date, Time}, _Message, _Metadata} = pop(),
  700. ?assertEqual(nomatch, binary:match(iolist_to_binary(Time), <<"UTC">>)),
  701. ok
  702. end
  703. },
  704. {"dates should be UTC if SASL is configured as UTC",
  705. fun() ->
  706. application:set_env(sasl, utc_log, true),
  707. eRum:warning("so long, and thanks for all the fish"),
  708. application:set_env(sasl, utc_log, false),
  709. ?assertEqual(1, count()),
  710. {_Level, {_Date, Time}, _Message, _Metadata} = pop(),
  711. ?assertNotEqual(nomatch, binary:match(iolist_to_binary(Time), <<"UTC">>)),
  712. ok
  713. end
  714. }
  715. ]
  716. }.
  717. extra_sinks_test_() ->
  718. {foreach,
  719. fun setup_sink/0,
  720. fun cleanup/1,
  721. [
  722. {"observe that there is nothing up my sleeve",
  723. fun() ->
  724. ?assertEqual(undefined, pop(?TEST_SINK_EVENT)),
  725. ?assertEqual(0, count(?TEST_SINK_EVENT))
  726. end
  727. },
  728. {"logging works",
  729. fun() ->
  730. ?TEST_SINK_NAME:warning("test message"),
  731. ?assertEqual(1, count(?TEST_SINK_EVENT)),
  732. {Level, _Time, Message, _Metadata} = pop(?TEST_SINK_EVENT),
  733. ?assertMatch(Level, rumUtil:level_to_num(warning)),
  734. ?assertEqual("test message", Message),
  735. ok
  736. end
  737. },
  738. {"logging with arguments works",
  739. fun() ->
  740. ?TEST_SINK_NAME:warning("test message ~p", [self()]),
  741. ?assertEqual(1, count(?TEST_SINK_EVENT)),
  742. {Level, _Time, Message, _Metadata} = pop(?TEST_SINK_EVENT),
  743. ?assertMatch(Level, rumUtil:level_to_num(warning)),
  744. ?assertEqual(lists:flatten(io_lib:format("test message ~p", [self()])), lists:flatten(Message)),
  745. ok
  746. end
  747. },
  748. {"variables inplace of literals in logging statements work",
  749. fun() ->
  750. ?assertEqual(0, count(?TEST_SINK_EVENT)),
  751. Attr = [{a, alpha}, {b, beta}],
  752. Fmt = "format ~p",
  753. Args = [world],
  754. ?TEST_SINK_NAME:info(Attr, "hello"),
  755. ?TEST_SINK_NAME:info(Attr, "hello ~p", [world]),
  756. ?TEST_SINK_NAME:info(Fmt, [world]),
  757. ?TEST_SINK_NAME:info("hello ~p", Args),
  758. ?TEST_SINK_NAME:info(Attr, "hello ~p", Args),
  759. ?TEST_SINK_NAME:info([{d, delta}, {g, gamma}], Fmt, Args),
  760. ?assertEqual(6, count(?TEST_SINK_EVENT)),
  761. {_Level, _Time, Message, Metadata} = pop(?TEST_SINK_EVENT),
  762. ?assertMatch([{a, alpha}, {b, beta} | _], Metadata),
  763. ?assertEqual("hello", lists:flatten(Message)),
  764. {_Level, _Time2, Message2, _Metadata2} = pop(?TEST_SINK_EVENT),
  765. ?assertEqual("hello world", lists:flatten(Message2)),
  766. {_Level, _Time3, Message3, _Metadata3} = pop(?TEST_SINK_EVENT),
  767. ?assertEqual("format world", lists:flatten(Message3)),
  768. {_Level, _Time4, Message4, _Metadata4} = pop(?TEST_SINK_EVENT),
  769. ?assertEqual("hello world", lists:flatten(Message4)),
  770. {_Level, _Time5, Message5, _Metadata5} = pop(?TEST_SINK_EVENT),
  771. ?assertEqual("hello world", lists:flatten(Message5)),
  772. {_Level, _Time6, Message6, Metadata6} = pop(?TEST_SINK_EVENT),
  773. ?assertMatch([{d, delta}, {g, gamma} | _], Metadata6),
  774. ?assertEqual("format world", lists:flatten(Message6)),
  775. ok
  776. end
  777. },
  778. {"stopped trace stops and removes its event handler - test sink (gh#267)",
  779. fun() ->
  780. Sink = ?TEST_SINK_EVENT,
  781. StartHandlers = gen_event:which_handlers(Sink),
  782. {_, T0} = lager_config:get({Sink, loglevel}),
  783. StartGlobal = lager_config:global_get(handlers),
  784. ?assertEqual([], T0),
  785. {ok, TestTrace1} = eRum:trace_file("/tmp/test", [{sink, Sink}, {a, b}]),
  786. MidHandlers = gen_event:which_handlers(Sink),
  787. {ok, TestTrace2} = eRum:trace_file("/tmp/test", [{sink, Sink}, {c, d}]),
  788. MidHandlers = gen_event:which_handlers(Sink),
  789. ?assertEqual(length(StartHandlers) + 1, length(MidHandlers)),
  790. MidGlobal = lager_config:global_get(handlers),
  791. ?assertEqual(length(StartGlobal) + 1, length(MidGlobal)),
  792. {_, T1} = lager_config:get({Sink, loglevel}),
  793. ?assertEqual(2, length(T1)),
  794. ok = eRum:stop_trace(TestTrace1),
  795. {_, T2} = lager_config:get({Sink, loglevel}),
  796. ?assertEqual(1, length(T2)),
  797. ?assertEqual(length(StartHandlers) + 1, length(
  798. gen_event:which_handlers(Sink))),
  799. ?assertEqual(length(StartGlobal) + 1, length(lager_config:global_get(handlers))),
  800. ok = eRum:stop_trace(TestTrace2),
  801. EndHandlers = gen_event:which_handlers(Sink),
  802. EndGlobal = lager_config:global_get(handlers),
  803. {_, T3} = lager_config:get({Sink, loglevel}),
  804. ?assertEqual([], T3),
  805. ?assertEqual(StartHandlers, EndHandlers),
  806. ?assertEqual(StartGlobal, EndGlobal),
  807. ok
  808. end
  809. },
  810. {"log messages below the threshold are ignored",
  811. fun() ->
  812. ?assertEqual(0, count(?TEST_SINK_EVENT)),
  813. ?TEST_SINK_NAME:debug("this message will be ignored"),
  814. ?assertEqual(0, count(?TEST_SINK_EVENT)),
  815. ?assertEqual(0, count_ignored(?TEST_SINK_EVENT)),
  816. lager_config:set({?TEST_SINK_EVENT, loglevel}, {element(2, rumUtil:config_to_mask(debug)), []}),
  817. ?TEST_SINK_NAME:debug("this message should be ignored"),
  818. ?assertEqual(0, count(?TEST_SINK_EVENT)),
  819. ?assertEqual(1, count_ignored(?TEST_SINK_EVENT)),
  820. eRum:set_loglevel(?TEST_SINK_EVENT, ?MODULE, undefined, debug),
  821. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get({?TEST_SINK_EVENT, loglevel})),
  822. ?TEST_SINK_NAME:debug("this message should be logged"),
  823. ?assertEqual(1, count(?TEST_SINK_EVENT)),
  824. ?assertEqual(1, count_ignored(?TEST_SINK_EVENT)),
  825. ?assertEqual(debug, eRum:get_loglevel(?TEST_SINK_EVENT, ?MODULE)),
  826. ok
  827. end
  828. }
  829. ]
  830. }.
  831. setup_sink() ->
  832. error_logger:tty(false),
  833. application:load(lager),
  834. application:set_env(lager, handlers, []),
  835. application:set_env(lager, error_logger_redirect, false),
  836. application:set_env(lager, extra_sinks, [{?TEST_SINK_EVENT, [{handlers, [{?MODULE, info}]}]}]),
  837. eRum:start(),
  838. gen_event:call(lager_event, ?MODULE, flush),
  839. gen_event:call(?TEST_SINK_EVENT, ?MODULE, flush).
  840. setup() ->
  841. error_logger:tty(false),
  842. application:load(lager),
  843. application:set_env(lager, handlers, [{?MODULE, info}]),
  844. application:set_env(lager, error_logger_redirect, false),
  845. application:unset_env(lager, traces),
  846. eRum:start(),
  847. %% There is a race condition between the application start up, lager logging its own
  848. %% start up condition and several tests that count messages or parse the output of
  849. %% tests. When the lager start up message wins the race, it causes these tests
  850. %% which parse output or count message arrivals to fail.
  851. %%
  852. %% We introduce a sleep here to allow `flush' to arrive *after* the start up
  853. %% message has been received and processed.
  854. %%
  855. %% This race condition was first exposed during the work on
  856. %% 4b5260c4524688b545cc12da6baa2dfa4f2afec9 which introduced the lager
  857. %% manager killer PR.
  858. application:set_env(lager, suppress_supervisor_start_stop, true),
  859. application:set_env(lager, suppress_application_start_stop, true),
  860. timer:sleep(1000),
  861. gen_event:call(lager_event, ?MODULE, flush).
  862. cleanup(_) ->
  863. catch ets:delete(lager_config), %% kill the ets config table with fire
  864. application:stop(lager),
  865. application:stop(goldrush),
  866. error_logger:tty(true).
  867. crash(Type) ->
  868. spawn(fun() -> gen_server:call(crash, Type) end),
  869. timer:sleep(100),
  870. _ = gen_event:which_handlers(error_logger),
  871. ok.
  872. test_body(Expected, Actual) ->
  873. ExLen = length(Expected),
  874. {Body, Rest} = case length(Actual) > ExLen of
  875. true ->
  876. {string:substr(Actual, 1, ExLen),
  877. string:substr(Actual, (ExLen + 1))};
  878. _ ->
  879. {Actual, []}
  880. end,
  881. ?assertEqual(Expected, Body),
  882. % OTP-17 (and maybe later releases) may tack on additional info
  883. % about the failure, so if Actual starts with Expected (already
  884. % confirmed by having gotten past assertEqual above) and ends
  885. % with " line NNN" we can ignore what's in-between. By extension,
  886. % since there may not be line information appended at all, any
  887. % text we DO find is reportable, but not a test failure.
  888. case Rest of
  889. [] ->
  890. ok;
  891. _ ->
  892. % isolate the extra data and report it if it's not just
  893. % a line number indicator
  894. case re:run(Rest, "^.*( line \\d+)$", [{capture, [1]}]) of
  895. nomatch ->
  896. ?debugFmt(
  897. "Trailing data \"~s\" following \"~s\"",
  898. [Rest, Expected]);
  899. {match, [{0, _}]} ->
  900. % the whole sting is " line NNN"
  901. ok;
  902. {match, [{Off, _}]} ->
  903. ?debugFmt(
  904. "Trailing data \"~s\" following \"~s\"",
  905. [string:substr(Rest, 1, Off), Expected])
  906. end
  907. end.
  908. error_logger_redirect_crash_setup() ->
  909. error_logger:tty(false),
  910. application:load(lager),
  911. application:set_env(lager, error_logger_redirect, true),
  912. application:set_env(lager, handlers, [{?MODULE, error}]),
  913. eRum:start(),
  914. crash:start(),
  915. lager_event.
  916. error_logger_redirect_crash_setup_sink() ->
  917. error_logger:tty(false),
  918. application:load(lager),
  919. application:set_env(lager, error_logger_redirect, true),
  920. application:unset_env(lager, handlers),
  921. application:set_env(lager, extra_sinks, [
  922. {error_logger_lager_event, [
  923. {handlers, [{?MODULE, error}]}]}]),
  924. eRum:start(),
  925. crash:start(),
  926. error_logger_lager_event.
  927. error_logger_redirect_crash_cleanup(_Sink) ->
  928. application:stop(lager),
  929. application:stop(goldrush),
  930. application:unset_env(lager, extra_sinks),
  931. case whereis(crash) of
  932. undefined -> ok;
  933. Pid -> exit(Pid, kill)
  934. end,
  935. error_logger:tty(true).
  936. crash_fsm_setup() ->
  937. error_logger:tty(false),
  938. application:load(lager),
  939. application:set_env(lager, error_logger_redirect, true),
  940. application:set_env(lager, handlers, [{?MODULE, error}]),
  941. eRum:start(),
  942. crash_fsm:start(),
  943. crash_statem:start(),
  944. eRum:log(error, self(), "flush flush"),
  945. timer:sleep(100),
  946. gen_event:call(lager_event, ?MODULE, flush),
  947. lager_event.
  948. crash_fsm_sink_setup() ->
  949. ErrorSink = error_logger_lager_event,
  950. error_logger:tty(false),
  951. application:load(lager),
  952. application:set_env(lager, error_logger_redirect, true),
  953. application:set_env(lager, handlers, []),
  954. application:set_env(lager, extra_sinks, [{ErrorSink, [{handlers, [{?MODULE, error}]}]}]),
  955. eRum:start(),
  956. crash_fsm:start(),
  957. crash_statem:start(),
  958. eRum:log(ErrorSink, error, self(), "flush flush", []),
  959. timer:sleep(100),
  960. flush(ErrorSink),
  961. ErrorSink.
  962. crash_fsm_cleanup(_Sink) ->
  963. application:stop(lager),
  964. application:stop(goldrush),
  965. application:unset_env(lager, extra_sinks),
  966. lists:foreach(fun(N) -> kill_crasher(N) end, [crash_fsm, crash_statem]),
  967. error_logger:tty(true).
  968. kill_crasher(RegName) ->
  969. case whereis(RegName) of
  970. undefined -> ok;
  971. Pid -> exit(Pid, kill)
  972. end.
  973. spawn_fsm_crash(Module, Function, Args) ->
  974. spawn(fun() -> erlang:apply(Module, Function, Args) end),
  975. timer:sleep(100),
  976. _ = gen_event:which_handlers(error_logger),
  977. ok.
  978. crash_fsm_test_() ->
  979. TestBody = fun(Name, FsmModule, FSMFunc, FSMArgs, Expected) ->
  980. fun(Sink) ->
  981. {Name,
  982. fun() ->
  983. case {FsmModule =:= crash_statem, rumUtil:otp_version() < 19} of
  984. {true, true} -> ok;
  985. _ ->
  986. Pid = whereis(FsmModule),
  987. spawn_fsm_crash(FsmModule, FSMFunc, FSMArgs),
  988. {Level, _, Msg, Metadata} = pop(Sink),
  989. test_body(Expected, lists:flatten(Msg)),
  990. ?assertEqual(Pid, proplists:get_value(pid, Metadata)),
  991. ?assertEqual(rumUtil:level_to_num(error), Level)
  992. end
  993. end
  994. }
  995. end
  996. end,
  997. Tests = [
  998. fun(Sink) ->
  999. {"again, there is nothing up my sleeve",
  1000. fun() ->
  1001. ?assertEqual(undefined, pop(Sink)),
  1002. ?assertEqual(0, count(Sink))
  1003. end
  1004. }
  1005. end,
  1006. TestBody("gen_fsm crash", crash_fsm, crash, [], "gen_fsm crash_fsm in state state1 terminated with reason: call to undefined function crash_fsm:state1/3 from gen_fsm:handle_msg/"),
  1007. TestBody("gen_statem crash", crash_statem, crash, [], "gen_statem crash_statem in state state1 terminated with reason: no function clause matching crash_statem:handle"),
  1008. TestBody("gen_statem stop", crash_statem, stop, [explode], "gen_statem crash_statem in state state1 terminated with reason: explode"),
  1009. TestBody("gen_statem timeout", crash_statem, timeout, [], "gen_statem crash_statem in state state1 terminated with reason: timeout")
  1010. ],
  1011. {"FSM crash output tests", [
  1012. {"Default sink",
  1013. {foreach,
  1014. fun crash_fsm_setup/0,
  1015. fun crash_fsm_cleanup/1,
  1016. Tests}},
  1017. {"Error logger sink",
  1018. {foreach,
  1019. fun crash_fsm_sink_setup/0,
  1020. fun crash_fsm_cleanup/1,
  1021. Tests}}
  1022. ]}.
  1023. error_logger_redirect_crash_test_() ->
  1024. TestBody = fun(Name, CrashReason, Expected) ->
  1025. fun(Sink) ->
  1026. {Name,
  1027. fun() ->
  1028. Pid = whereis(crash),
  1029. crash(CrashReason),
  1030. {Level, _, Msg, Metadata} = pop(Sink),
  1031. test_body(Expected, lists:flatten(Msg)),
  1032. ?assertEqual(Pid, proplists:get_value(pid, Metadata)),
  1033. ?assertEqual(rumUtil:level_to_num(error), Level)
  1034. end
  1035. }
  1036. end
  1037. end,
  1038. Tests = [
  1039. fun(Sink) ->
  1040. {"again, there is nothing up my sleeve",
  1041. fun() ->
  1042. ?assertEqual(undefined, pop(Sink)),
  1043. ?assertEqual(0, count(Sink))
  1044. end
  1045. }
  1046. end,
  1047. TestBody("bad return value", bad_return, "gen_server crash terminated with reason: bad return value: bleh"),
  1048. TestBody("bad return value with string", bad_return_string, "gen_server crash terminated with reason: bad return value: {tuple,{tuple,\"string\"}}"),
  1049. TestBody("bad return uncaught throw", throw, "gen_server crash terminated with reason: bad return value: a_ball"),
  1050. TestBody("case clause", case_clause, "gen_server crash terminated with reason: no case clause matching {} in crash:handle_call/3"),
  1051. TestBody("case clause string", case_clause_string, "gen_server crash terminated with reason: no case clause matching \"crash\" in crash:handle_call/3"),
  1052. TestBody("function clause", function_clause, "gen_server crash terminated with reason: no function clause matching crash:function({})"),
  1053. TestBody("if clause", if_clause, "gen_server crash terminated with reason: no true branch found while evaluating if expression in crash:handle_call/3"),
  1054. TestBody("try clause", try_clause, "gen_server crash terminated with reason: no try clause matching [] in crash:handle_call/3"),
  1055. TestBody("undefined function", undef, "gen_server crash terminated with reason: call to undefined function crash:booger/0 from crash:handle_call/3"),
  1056. TestBody("bad math", badarith, "gen_server crash terminated with reason: bad arithmetic expression in crash:handle_call/3"),
  1057. TestBody("bad match", badmatch, "gen_server crash terminated with reason: no match of right hand value {} in crash:handle_call/3"),
  1058. TestBody("bad arity", badarity, "gen_server crash terminated with reason: fun called with wrong arity of 1 instead of 3 in crash:handle_call/3"),
  1059. TestBody("bad arg1", badarg1, "gen_server crash terminated with reason: bad argument in crash:handle_call/3"),
  1060. TestBody("bad arg2", badarg2, "gen_server crash terminated with reason: bad argument in call to erlang:iolist_to_binary([\"foo\",bar]) in crash:handle_call/3"),
  1061. TestBody("bad record", badrecord, "gen_server crash terminated with reason: bad record state in crash:handle_call/3"),
  1062. TestBody("noproc", noproc, "gen_server crash terminated with reason: no such process or port in call to gen_event:call(foo, bar, baz)"),
  1063. TestBody("noproc_proc_lib", noproc_proc_lib, "gen_server crash terminated with reason: no such process or port in call to proc_lib:stop/3"),
  1064. TestBody("badfun", badfun, "gen_server crash terminated with reason: bad function booger in crash:handle_call/3")
  1065. ],
  1066. {"Error logger redirect crash", [
  1067. {"Redirect to default sink",
  1068. {foreach,
  1069. fun error_logger_redirect_crash_setup/0,
  1070. fun error_logger_redirect_crash_cleanup/1,
  1071. Tests}},
  1072. {"Redirect to error_logger_lager_event sink",
  1073. {foreach,
  1074. fun error_logger_redirect_crash_setup_sink/0,
  1075. fun error_logger_redirect_crash_cleanup/1,
  1076. Tests}}
  1077. ]}.
  1078. error_logger_redirect_setup() ->
  1079. error_logger:tty(false),
  1080. application:load(lager),
  1081. application:set_env(lager, error_logger_redirect, true),
  1082. application:set_env(lager, handlers, [{?MODULE, info}]),
  1083. application:set_env(lager, suppress_supervisor_start_stop, false),
  1084. application:set_env(lager, suppress_application_start_stop, false),
  1085. eRum:start(),
  1086. eRum:log(error, self(), "flush flush"),
  1087. timer:sleep(1000),
  1088. gen_event:call(lager_event, ?MODULE, flush),
  1089. lager_event.
  1090. error_logger_redirect_setup_sink() ->
  1091. error_logger:tty(false),
  1092. application:load(lager),
  1093. application:set_env(lager, error_logger_redirect, true),
  1094. application:unset_env(lager, handlers),
  1095. application:set_env(lager, extra_sinks, [
  1096. {error_logger_lager_event, [
  1097. {handlers, [{?MODULE, info}]}]}]),
  1098. application:set_env(lager, suppress_supervisor_start_stop, false),
  1099. application:set_env(lager, suppress_application_start_stop, false),
  1100. eRum:start(),
  1101. eRum:log(error_logger_lager_event, error, self(), "flush flush", []),
  1102. timer:sleep(1000),
  1103. gen_event:call(error_logger_lager_event, ?MODULE, flush),
  1104. error_logger_lager_event.
  1105. error_logger_redirect_cleanup(_) ->
  1106. application:stop(lager),
  1107. application:stop(goldrush),
  1108. application:unset_env(lager, extra_sinks),
  1109. error_logger:tty(true).
  1110. error_logger_redirect_test_() ->
  1111. Tests = [
  1112. {"error reports are printed",
  1113. fun(Sink) ->
  1114. sync_error_logger:error_report([{this, is}, a, {silly, format}]),
  1115. _ = gen_event:which_handlers(error_logger),
  1116. {Level, _, Msg, Metadata} = pop(Sink),
  1117. ?assertEqual(rumUtil:level_to_num(error), Level),
  1118. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1119. Expected = "this: is, a, silly: format",
  1120. ?assertEqual(Expected, lists:flatten(Msg))
  1121. end
  1122. },
  1123. {"string error reports are printed",
  1124. fun(Sink) ->
  1125. sync_error_logger:error_report("this is less silly"),
  1126. _ = gen_event:which_handlers(error_logger),
  1127. {Level, _, Msg, Metadata} = pop(Sink),
  1128. ?assertEqual(rumUtil:level_to_num(error), Level),
  1129. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1130. Expected = "this is less silly",
  1131. ?assertEqual(Expected, lists:flatten(Msg))
  1132. end
  1133. },
  1134. {"error messages are printed",
  1135. fun(Sink) ->
  1136. sync_error_logger:error_msg("doom, doom has come upon you all"),
  1137. _ = gen_event:which_handlers(error_logger),
  1138. {Level, _, Msg, Metadata} = pop(Sink),
  1139. ?assertEqual(rumUtil:level_to_num(error), Level),
  1140. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1141. Expected = "doom, doom has come upon you all",
  1142. ?assertEqual(Expected, lists:flatten(Msg))
  1143. end
  1144. },
  1145. {"error messages with unicode characters in Args are printed",
  1146. fun(Sink) ->
  1147. sync_error_logger:error_msg("~ts", ["Привет!"]),
  1148. _ = gen_event:which_handlers(error_logger),
  1149. {Level, _, Msg, Metadata} = pop(Sink),
  1150. ?assertEqual(rumUtil:level_to_num(error), Level),
  1151. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1152. ?assertEqual("Привет!", lists:flatten(Msg))
  1153. end
  1154. },
  1155. {"error messages are truncated at 4096 characters",
  1156. fun(Sink) ->
  1157. sync_error_logger:error_msg("doom, doom has come upon you all ~p", [string:copies("doom", 10000)]),
  1158. _ = gen_event:which_handlers(error_logger),
  1159. {_, _, Msg, _Metadata} = pop(Sink),
  1160. ?assert(length(lists:flatten(Msg)) < 5100)
  1161. end
  1162. },
  1163. {"info reports are printed",
  1164. fun(Sink) ->
  1165. sync_error_logger:info_report([{this, is}, a, {silly, format}]),
  1166. _ = gen_event:which_handlers(error_logger),
  1167. {Level, _, Msg, Metadata} = pop(Sink),
  1168. ?assertEqual(rumUtil:level_to_num(info), Level),
  1169. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1170. Expected = "this: is, a, silly: format",
  1171. ?assertEqual(Expected, lists:flatten(Msg))
  1172. end
  1173. },
  1174. {"info reports are truncated at 4096 characters",
  1175. fun(Sink) ->
  1176. sync_error_logger:info_report([[{this, is}, a, {silly, format}] || _ <- lists:seq(0, 600)]),
  1177. _ = gen_event:which_handlers(error_logger),
  1178. {Level, _, Msg, Metadata} = pop(Sink),
  1179. ?assertEqual(rumUtil:level_to_num(info), Level),
  1180. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1181. ?assert(length(lists:flatten(Msg)) < 5000)
  1182. end
  1183. },
  1184. {"single term info reports are printed",
  1185. fun(Sink) ->
  1186. sync_error_logger:info_report({foolish, bees}),
  1187. _ = gen_event:which_handlers(error_logger),
  1188. {Level, _, Msg, Metadata} = pop(Sink),
  1189. ?assertEqual(rumUtil:level_to_num(info), Level),
  1190. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1191. ?assertEqual("{foolish,bees}", lists:flatten(Msg))
  1192. end
  1193. },
  1194. {"single term error reports are printed",
  1195. fun(Sink) ->
  1196. sync_error_logger:error_report({foolish, bees}),
  1197. _ = gen_event:which_handlers(error_logger),
  1198. {Level, _, Msg, Metadata} = pop(Sink),
  1199. ?assertEqual(rumUtil:level_to_num(error), Level),
  1200. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1201. ?assertEqual("{foolish,bees}", lists:flatten(Msg))
  1202. end
  1203. },
  1204. {"string info reports are printed",
  1205. fun(Sink) ->
  1206. sync_error_logger:info_report("this is less silly"),
  1207. _ = gen_event:which_handlers(error_logger),
  1208. {Level, _, Msg, Metadata} = pop(Sink),
  1209. ?assertEqual(rumUtil:level_to_num(info), Level),
  1210. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1211. ?assertEqual("this is less silly", lists:flatten(Msg))
  1212. end
  1213. },
  1214. {"string info reports are truncated at 4096 characters",
  1215. fun(Sink) ->
  1216. sync_error_logger:info_report(string:copies("this is less silly", 1000)),
  1217. _ = gen_event:which_handlers(error_logger),
  1218. {Level, _, Msg, Metadata} = pop(Sink),
  1219. ?assertEqual(rumUtil:level_to_num(info), Level),
  1220. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1221. ?assert(length(lists:flatten(Msg)) < 5100)
  1222. end
  1223. },
  1224. {"strings in a mixed report are printed as strings",
  1225. fun(Sink) ->
  1226. sync_error_logger:info_report(["this is less silly", {than, "this"}]),
  1227. _ = gen_event:which_handlers(error_logger),
  1228. {Level, _, Msg, Metadata} = pop(Sink),
  1229. ?assertEqual(rumUtil:level_to_num(info), Level),
  1230. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1231. ?assertEqual("\"this is less silly\", than: \"this\"", lists:flatten(Msg))
  1232. end
  1233. },
  1234. {"info messages are printed",
  1235. fun(Sink) ->
  1236. sync_error_logger:info_msg("doom, doom has come upon you all"),
  1237. _ = gen_event:which_handlers(error_logger),
  1238. {Level, _, Msg, Metadata} = pop(Sink),
  1239. ?assertEqual(rumUtil:level_to_num(info), Level),
  1240. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1241. ?assertEqual("doom, doom has come upon you all", lists:flatten(Msg))
  1242. end
  1243. },
  1244. {"info messages are truncated at 4096 characters",
  1245. fun(Sink) ->
  1246. sync_error_logger:info_msg("doom, doom has come upon you all ~p", [string:copies("doom", 10000)]),
  1247. _ = gen_event:which_handlers(error_logger),
  1248. {Level, _, Msg, Metadata} = pop(Sink),
  1249. ?assertEqual(rumUtil:level_to_num(info), Level),
  1250. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1251. ?assert(length(lists:flatten(Msg)) < 5100)
  1252. end
  1253. },
  1254. {"info messages with unicode characters in Args are printed",
  1255. fun(Sink) ->
  1256. sync_error_logger:info_msg("~ts", ["Привет!"]),
  1257. _ = gen_event:which_handlers(error_logger),
  1258. {Level, _, Msg, Metadata} = pop(Sink),
  1259. ?assertEqual(rumUtil:level_to_num(info), Level),
  1260. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1261. ?assertEqual("Привет!", lists:flatten(Msg))
  1262. end
  1263. },
  1264. {"warning messages with unicode characters in Args are printed",
  1265. %% The next 4 tests need to store the current value of
  1266. %% `error_logger:warning_map/0' into a process dictionary
  1267. %% key `warning_map' so that the error message level used
  1268. %% to process the log messages will match what lager
  1269. %% expects.
  1270. %%
  1271. %% The atom returned by `error_logger:warning_map/0'
  1272. %% changed between OTP 17 and 18 (and later releases)
  1273. %%
  1274. %% `warning_map' is consumed in the `test/sync_error_logger.erl'
  1275. %% module. The default message level used in sync_error_logger
  1276. %% was fine for OTP releases through 17 and then broke
  1277. %% when 18 was released. By storing the expected value
  1278. %% in the process dictionary, sync_error_logger will
  1279. %% use the correct message level to process the
  1280. %% messages and these tests will no longer
  1281. %% break.
  1282. fun(Sink) ->
  1283. Lvl = error_logger:warning_map(),
  1284. put(warning_map, Lvl),
  1285. sync_error_logger:warning_msg("~ts", ["Привет!"]),
  1286. _ = gen_event:which_handlers(error_logger),
  1287. {Level, _, Msg, Metadata} = pop(Sink),
  1288. ?assertEqual(rumUtil:level_to_num(Lvl), Level),
  1289. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1290. ?assertEqual("Привет!", lists:flatten(Msg))
  1291. end
  1292. },
  1293. {"warning messages are printed at the correct level",
  1294. fun(Sink) ->
  1295. Lvl = error_logger:warning_map(),
  1296. put(warning_map, Lvl),
  1297. sync_error_logger:warning_msg("doom, doom has come upon you all"),
  1298. _ = gen_event:which_handlers(error_logger),
  1299. {Level, _, Msg, Metadata} = pop(Sink),
  1300. ?assertEqual(rumUtil:level_to_num(Lvl), Level),
  1301. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1302. ?assertEqual("doom, doom has come upon you all", lists:flatten(Msg))
  1303. end
  1304. },
  1305. {"warning reports are printed at the correct level",
  1306. fun(Sink) ->
  1307. Lvl = error_logger:warning_map(),
  1308. put(warning_map, Lvl),
  1309. sync_error_logger:warning_report([{i, like}, pie]),
  1310. _ = gen_event:which_handlers(error_logger),
  1311. {Level, _, Msg, Metadata} = pop(Sink),
  1312. ?assertEqual(rumUtil:level_to_num(Lvl), Level),
  1313. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1314. ?assertEqual("i: like, pie", lists:flatten(Msg))
  1315. end
  1316. },
  1317. {"single term warning reports are printed at the correct level",
  1318. fun(Sink) ->
  1319. Lvl = error_logger:warning_map(),
  1320. put(warning_map, Lvl),
  1321. sync_error_logger:warning_report({foolish, bees}),
  1322. _ = gen_event:which_handlers(error_logger),
  1323. {Level, _, Msg, Metadata} = pop(Sink),
  1324. ?assertEqual(rumUtil:level_to_num(Lvl), Level),
  1325. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1326. ?assertEqual("{foolish,bees}", lists:flatten(Msg))
  1327. end
  1328. },
  1329. {"application stop reports",
  1330. fun(Sink) ->
  1331. sync_error_logger:info_report([{application, foo}, {exited, quittin_time}, {type, lazy}]),
  1332. _ = gen_event:which_handlers(error_logger),
  1333. {Level, _, Msg, Metadata} = pop(Sink),
  1334. ?assertEqual(rumUtil:level_to_num(info), Level),
  1335. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1336. ?assertEqual("Application foo exited with reason: quittin_time", lists:flatten(Msg))
  1337. end
  1338. },
  1339. {"supervisor reports",
  1340. fun(Sink) ->
  1341. sync_error_logger:error_report(supervisor_report, [{errorContext, france}, {offender, [{name, mini_steve}, {mfargs, {a, b, [c]}}, {pid, bleh}]}, {reason, fired}, {supervisor, {local, steve}}]),
  1342. _ = gen_event:which_handlers(error_logger),
  1343. {Level, _, Msg, Metadata} = pop(Sink),
  1344. ?assertEqual(rumUtil:level_to_num(error), Level),
  1345. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1346. ?assertEqual("Supervisor steve had child mini_steve started with a:b(c) at bleh exit with reason fired in context france", lists:flatten(Msg))
  1347. end
  1348. },
  1349. {"supervisor reports with real error",
  1350. fun(Sink) ->
  1351. sync_error_logger:error_report(supervisor_report, [{errorContext, france}, {offender, [{name, mini_steve}, {mfargs, {a, b, [c]}}, {pid, bleh}]}, {reason, {function_clause, [{crash, handle_info, [foo]}]}}, {supervisor, {local, steve}}]),
  1352. _ = gen_event:which_handlers(error_logger),
  1353. {Level, _, Msg, Metadata} = pop(Sink),
  1354. ?assertEqual(rumUtil:level_to_num(error), Level),
  1355. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1356. ?assertEqual("Supervisor steve had child mini_steve started with a:b(c) at bleh exit with reason no function clause matching crash:handle_info(foo) in context france", lists:flatten(Msg))
  1357. end
  1358. },
  1359. {"supervisor reports with real error and pid",
  1360. fun(Sink) ->
  1361. sync_error_logger:error_report(supervisor_report, [{errorContext, france}, {offender, [{name, mini_steve}, {mfargs, {a, b, [c]}}, {pid, bleh}]}, {reason, {function_clause, [{crash, handle_info, [foo]}]}}, {supervisor, somepid}]),
  1362. _ = gen_event:which_handlers(error_logger),
  1363. {Level, _, Msg, Metadata} = pop(Sink),
  1364. ?assertEqual(rumUtil:level_to_num(error), Level),
  1365. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1366. ?assertEqual("Supervisor somepid had child mini_steve started with a:b(c) at bleh exit with reason no function clause matching crash:handle_info(foo) in context france", lists:flatten(Msg))
  1367. end
  1368. },
  1369. {"supervisor_bridge reports",
  1370. fun(Sink) ->
  1371. sync_error_logger:error_report(supervisor_report, [{errorContext, france}, {offender, [{mod, mini_steve}, {pid, bleh}]}, {reason, fired}, {supervisor, {local, steve}}]),
  1372. _ = gen_event:which_handlers(error_logger),
  1373. {Level, _, Msg, Metadata} = pop(Sink),
  1374. ?assertEqual(rumUtil:level_to_num(error), Level),
  1375. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1376. ?assertEqual("Supervisor steve had child at module mini_steve at bleh exit with reason fired in context france", lists:flatten(Msg))
  1377. end
  1378. },
  1379. {"application progress report",
  1380. fun(Sink) ->
  1381. sync_error_logger:info_report(progress, [{application, foo}, {started_at, node()}]),
  1382. _ = gen_event:which_handlers(error_logger),
  1383. {Level, _, Msg, Metadata} = pop(Sink),
  1384. ?assertEqual(rumUtil:level_to_num(info), Level),
  1385. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1386. Expected = lists:flatten(io_lib:format("Application foo started on node ~w", [node()])),
  1387. ?assertEqual(Expected, lists:flatten(Msg))
  1388. end
  1389. },
  1390. {"supervisor progress report",
  1391. fun(Sink) ->
  1392. eRum:set_loglevel(Sink, ?MODULE, undefined, debug),
  1393. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get({Sink, loglevel})),
  1394. sync_error_logger:info_report(progress, [{supervisor, {local, foo}}, {started, [{mfargs, {foo, bar, 1}}, {pid, baz}]}]),
  1395. _ = gen_event:which_handlers(error_logger),
  1396. {Level, _, Msg, Metadata} = pop(Sink),
  1397. ?assertEqual(rumUtil:level_to_num(debug), Level),
  1398. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1399. ?assertEqual("Supervisor foo started foo:bar/1 at pid baz", lists:flatten(Msg))
  1400. end
  1401. },
  1402. {"supervisor progress report with pid",
  1403. fun(Sink) ->
  1404. eRum:set_loglevel(Sink, ?MODULE, undefined, debug),
  1405. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get({Sink, loglevel})),
  1406. sync_error_logger:info_report(progress, [{supervisor, somepid}, {started, [{mfargs, {foo, bar, 1}}, {pid, baz}]}]),
  1407. _ = gen_event:which_handlers(error_logger),
  1408. {Level, _, Msg, Metadata} = pop(Sink),
  1409. ?assertEqual(rumUtil:level_to_num(debug), Level),
  1410. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1411. ?assertEqual("Supervisor somepid started foo:bar/1 at pid baz", lists:flatten(Msg))
  1412. end
  1413. },
  1414. {"crash report for emfile",
  1415. fun(Sink) ->
  1416. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, emfile, [{stack, trace, 1}]}}], []]),
  1417. _ = gen_event:which_handlers(error_logger),
  1418. {Level, _, Msg, Metadata} = pop(Sink),
  1419. ?assertEqual(rumUtil:level_to_num(error), Level),
  1420. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1421. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: maximum number of file descriptors exhausted, check ulimit -n", [self()])),
  1422. ?assertEqual(Expected, lists:flatten(Msg))
  1423. end
  1424. },
  1425. {"crash report for system process limit",
  1426. fun(Sink) ->
  1427. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, spawn, 1}]}}], []]),
  1428. _ = gen_event:which_handlers(error_logger),
  1429. {Level, _, Msg, Metadata} = pop(Sink),
  1430. ?assertEqual(rumUtil:level_to_num(error), Level),
  1431. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1432. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: maximum number of processes exceeded", [self()])),
  1433. ?assertEqual(Expected, lists:flatten(Msg))
  1434. end
  1435. },
  1436. {"crash report for system process limit2",
  1437. fun(Sink) ->
  1438. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, spawn_opt, 1}]}}], []]),
  1439. _ = gen_event:which_handlers(error_logger),
  1440. {Level, _, Msg, Metadata} = pop(Sink),
  1441. ?assertEqual(rumUtil:level_to_num(error), Level),
  1442. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1443. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: maximum number of processes exceeded", [self()])),
  1444. ?assertEqual(Expected, lists:flatten(Msg))
  1445. end
  1446. },
  1447. {"crash report for system port limit",
  1448. fun(Sink) ->
  1449. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, open_port, 1}]}}], []]),
  1450. _ = gen_event:which_handlers(error_logger),
  1451. {Level, _, Msg, Metadata} = pop(Sink),
  1452. ?assertEqual(rumUtil:level_to_num(error), Level),
  1453. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1454. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: maximum number of ports exceeded", [self()])),
  1455. ?assertEqual(Expected, lists:flatten(Msg))
  1456. end
  1457. },
  1458. {"crash report for system port limit",
  1459. fun(Sink) ->
  1460. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, list_to_atom, 1}]}}], []]),
  1461. _ = gen_event:which_handlers(error_logger),
  1462. {Level, _, Msg, Metadata} = pop(Sink),
  1463. ?assertEqual(rumUtil:level_to_num(error), Level),
  1464. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1465. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: tried to create an atom larger than 255, or maximum atom count exceeded", [self()])),
  1466. ?assertEqual(Expected, lists:flatten(Msg))
  1467. end
  1468. },
  1469. {"crash report for system ets table limit",
  1470. fun(Sink) ->
  1471. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, test}, {error_info, {error, system_limit, [{ets, new, [segment_offsets, [ordered_set, public]]}, {mi_segment, open_write, 1}, {mi_buffer_converter, handle_cast, 2}, {gen_server, handle_msg, 5}, {proc_lib, init_p_do_apply, 3}]}}], []]),
  1472. _ = gen_event:which_handlers(error_logger),
  1473. {Level, _, Msg, Metadata} = pop(Sink),
  1474. ?assertEqual(rumUtil:level_to_num(error), Level),
  1475. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1476. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: maximum number of ETS tables exceeded", [test])),
  1477. ?assertEqual(Expected, lists:flatten(Msg))
  1478. end
  1479. },
  1480. {"crash report for unknown system limit should be truncated at 500 characters",
  1481. fun(Sink) ->
  1482. sync_error_logger:error_report(crash_report, [[{pid, self()}, {error_info, {error, system_limit, [{wtf, boom, [string:copies("aaaa", 4096)]}]}}], []]),
  1483. _ = gen_event:which_handlers(error_logger),
  1484. {_, _, Msg, _Metadata} = pop(Sink),
  1485. ?assert(length(lists:flatten(Msg)) > 550),
  1486. ?assert(length(lists:flatten(Msg)) < 600)
  1487. end
  1488. },
  1489. {"crash reports for 'special processes' should be handled right - function_clause",
  1490. fun(Sink) ->
  1491. {ok, Pid} = special_process:start(),
  1492. unlink(Pid),
  1493. Pid ! function_clause,
  1494. timer:sleep(500),
  1495. _ = gen_event:which_handlers(error_logger),
  1496. {_, _, Msg, _Metadata} = pop(Sink),
  1497. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~p with 0 neighbours crashed with reason: no function clause matching special_process:foo(bar)",
  1498. [Pid])),
  1499. test_body(Expected, lists:flatten(Msg))
  1500. end
  1501. },
  1502. {"crash reports for 'special processes' should be handled right - case_clause",
  1503. fun(Sink) ->
  1504. {ok, Pid} = special_process:start(),
  1505. unlink(Pid),
  1506. Pid ! {case_clause, wtf},
  1507. timer:sleep(500),
  1508. _ = gen_event:which_handlers(error_logger),
  1509. {_, _, Msg, _Metadata} = pop(Sink),
  1510. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~p with 0 neighbours crashed with reason: no case clause matching wtf in special_process:loop/0",
  1511. [Pid])),
  1512. test_body(Expected, lists:flatten(Msg))
  1513. end
  1514. },
  1515. {"crash reports for 'special processes' should be handled right - exit",
  1516. fun(Sink) ->
  1517. {ok, Pid} = special_process:start(),
  1518. unlink(Pid),
  1519. Pid ! exit,
  1520. timer:sleep(500),
  1521. _ = gen_event:which_handlers(error_logger),
  1522. {_, _, Msg, _Metadata} = pop(Sink),
  1523. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~p with 0 neighbours exited with reason: byebye in special_process:loop/0",
  1524. [Pid])),
  1525. test_body(Expected, lists:flatten(Msg))
  1526. end
  1527. },
  1528. {"crash reports for 'special processes' should be handled right - error",
  1529. fun(Sink) ->
  1530. {ok, Pid} = special_process:start(),
  1531. unlink(Pid),
  1532. Pid ! error,
  1533. timer:sleep(500),
  1534. _ = gen_event:which_handlers(error_logger),
  1535. {_, _, Msg, _Metadata} = pop(Sink),
  1536. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~p with 0 neighbours crashed with reason: mybad in special_process:loop/0",
  1537. [Pid])),
  1538. test_body(Expected, lists:flatten(Msg))
  1539. end
  1540. },
  1541. {"webmachine error reports",
  1542. fun(Sink) ->
  1543. Path = "/cgi-bin/phpmyadmin",
  1544. Reason = {error, {error, {badmatch, {error, timeout}},
  1545. [{myapp, dostuff, 2, [{file, "src/myapp.erl"}, {line, 123}]},
  1546. {webmachine_resource, resource_call, 3, [{file, "src/webmachine_resource.erl"}, {line, 169}]}]}},
  1547. sync_error_logger:error_msg("webmachine error: path=~p~n~p~n", [Path, Reason]),
  1548. _ = gen_event:which_handlers(error_logger),
  1549. {Level, _, Msg, Metadata} = pop(Sink),
  1550. ?assertEqual(rumUtil:level_to_num(error), Level),
  1551. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1552. ?assertEqual("Webmachine error at path \"/cgi-bin/phpmyadmin\" : no match of right hand value {error,timeout} in myapp:dostuff/2 line 123", lists:flatten(Msg))
  1553. end
  1554. },
  1555. {"Cowboy error reports, 8 arg version",
  1556. fun(Sink) ->
  1557. Stack = [{my_handler, init, 3, [{file, "src/my_handler.erl"}, {line, 123}]},
  1558. {cowboy_handler, handler_init, 4, [{file, "src/cowboy_handler.erl"}, {line, 169}]}],
  1559. sync_error_logger:error_msg(
  1560. "** Cowboy handler ~p terminating in ~p/~p~n"
  1561. " for the reason ~p:~p~n"
  1562. "** Options were ~p~n"
  1563. "** Request was ~p~n"
  1564. "** Stacktrace: ~p~n~n",
  1565. [my_handler, init, 3, error, {badmatch, {error, timeout}}, [],
  1566. "Request", Stack]),
  1567. _ = gen_event:which_handlers(error_logger),
  1568. {Level, _, Msg, Metadata} = pop(Sink),
  1569. ?assertEqual(rumUtil:level_to_num(error), Level),
  1570. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1571. ?assertEqual("Cowboy handler my_handler terminated in my_handler:init/3 with reason: no match of right hand value {error,timeout} in my_handler:init/3 line 123", lists:flatten(Msg))
  1572. end
  1573. },
  1574. {"Cowboy error reports, 10 arg version",
  1575. fun(Sink) ->
  1576. Stack = [{my_handler, somecallback, 3, [{file, "src/my_handler.erl"}, {line, 123}]},
  1577. {cowboy_handler, handler_init, 4, [{file, "src/cowboy_handler.erl"}, {line, 169}]}],
  1578. sync_error_logger:error_msg(
  1579. "** Cowboy handler ~p terminating in ~p/~p~n"
  1580. " for the reason ~p:~p~n** Message was ~p~n"
  1581. "** Options were ~p~n** Handler state was ~p~n"
  1582. "** Request was ~p~n** Stacktrace: ~p~n~n",
  1583. [my_handler, somecallback, 3, error, {badmatch, {error, timeout}}, hello, [],
  1584. {}, "Request", Stack]),
  1585. _ = gen_event:which_handlers(error_logger),
  1586. {Level, _, Msg, Metadata} = pop(Sink),
  1587. ?assertEqual(rumUtil:level_to_num(error), Level),
  1588. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1589. ?assertEqual("Cowboy handler my_handler terminated in my_handler:somecallback/3 with reason: no match of right hand value {error,timeout} in my_handler:somecallback/3 line 123", lists:flatten(Msg))
  1590. end
  1591. },
  1592. {"Cowboy error reports, 5 arg version",
  1593. fun(Sink) ->
  1594. sync_error_logger:error_msg(
  1595. "** Cowboy handler ~p terminating; "
  1596. "function ~p/~p was not exported~n"
  1597. "** Request was ~p~n** State was ~p~n~n",
  1598. [my_handler, to_json, 2, "Request", {}]),
  1599. _ = gen_event:which_handlers(error_logger),
  1600. {Level, _, Msg, Metadata} = pop(Sink),
  1601. ?assertEqual(rumUtil:level_to_num(error), Level),
  1602. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1603. ?assertEqual("Cowboy handler my_handler terminated with reason: call to undefined function my_handler:to_json/2", lists:flatten(Msg))
  1604. end
  1605. },
  1606. {"Cowboy error reports, 6 arg version",
  1607. fun(Sink) ->
  1608. Stack = [{app_http, init, 2, [{file, "app_http.erl"}, {line, 9}]},
  1609. {cowboy_handler, execute, 2, [{file, "cowboy_handler.erl"}, {line, 41}]}],
  1610. ConnectionPid = list_to_pid("<0.82.0>"),
  1611. sync_error_logger:error_msg(
  1612. "Ranch listener ~p, connection process ~p, stream ~p "
  1613. "had its request process ~p exit with reason "
  1614. "~999999p and stacktrace ~999999p~n",
  1615. [my_listner, ConnectionPid, 1, self(), {badmatch, 2}, Stack]),
  1616. _ = gen_event:which_handlers(error_logger),
  1617. {Level, _, Msg, Metadata} = pop(Sink),
  1618. ?assertEqual(rumUtil:level_to_num(error), Level),
  1619. ?assertEqual(self(), proplists:get_value(pid, Metadata)),
  1620. ?assertEqual("Cowboy stream 1 with ranch listener my_listner and "
  1621. "connection process <0.82.0> had its request process exit "
  1622. "with reason: no match of right hand value 2 "
  1623. "in app_http:init/2 line 9", lists:flatten(Msg))
  1624. end
  1625. },
  1626. {"messages should not be generated if they don't satisfy the threshold",
  1627. fun(Sink) ->
  1628. eRum:set_loglevel(Sink, ?MODULE, undefined, error),
  1629. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get({Sink, loglevel})),
  1630. sync_error_logger:info_report([hello, world]),
  1631. _ = gen_event:which_handlers(error_logger),
  1632. ?assertEqual(0, count(Sink)),
  1633. ?assertEqual(0, count_ignored(Sink)),
  1634. eRum:set_loglevel(Sink, ?MODULE, undefined, info),
  1635. ?assertEqual({?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get({Sink, loglevel})),
  1636. sync_error_logger:info_report([hello, world]),
  1637. _ = gen_event:which_handlers(error_logger),
  1638. ?assertEqual(1, count(Sink)),
  1639. ?assertEqual(0, count_ignored(Sink)),
  1640. eRum:set_loglevel(Sink, ?MODULE, undefined, error),
  1641. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get({Sink, loglevel})),
  1642. lager_config:set({Sink, loglevel}, {element(2, rumUtil:config_to_mask(debug)), []}),
  1643. sync_error_logger:info_report([hello, world]),
  1644. _ = gen_event:which_handlers(error_logger),
  1645. ?assertEqual(1, count(Sink)),
  1646. ?assertEqual(1, count_ignored(Sink))
  1647. end
  1648. }
  1649. ],
  1650. SinkTests = lists:map(
  1651. fun({Name, F}) ->
  1652. fun(Sink) -> {Name, fun() -> F(Sink) end} end
  1653. end,
  1654. Tests),
  1655. {"Error logger redirect", [
  1656. {"Redirect to default sink",
  1657. {foreach,
  1658. fun error_logger_redirect_setup/0,
  1659. fun error_logger_redirect_cleanup/1,
  1660. SinkTests}},
  1661. {"Redirect to error_logger_lager_event sink",
  1662. {foreach,
  1663. fun error_logger_redirect_setup_sink/0,
  1664. fun error_logger_redirect_cleanup/1,
  1665. SinkTests}}
  1666. ]}.
  1667. safe_format_test() ->
  1668. ?assertEqual("foo bar", lists:flatten(eRum:safe_format("~p ~p", [foo, bar], 1024))),
  1669. ?assertEqual("FORMAT ERROR: \"~p ~p ~p\" [foo,bar]", lists:flatten(eRum:safe_format("~p ~p ~p", [foo, bar], 1024))),
  1670. ok.
  1671. unsafe_format_test() ->
  1672. ?assertEqual("foo bar", lists:flatten(eRum:unsafe_format("~p ~p", [foo, bar]))),
  1673. ?assertEqual("FORMAT ERROR: \"~p ~p ~p\" [foo,bar]", lists:flatten(eRum:unsafe_format("~p ~p ~p", [foo, bar]))),
  1674. ok.
  1675. async_threshold_test_() ->
  1676. Cleanup = fun(Reset) ->
  1677. _ = error_logger:tty(false),
  1678. _ = application:stop(lager),
  1679. _ = application:stop(goldrush),
  1680. _ = application:unset_env(lager, async_threshold),
  1681. if
  1682. Reset ->
  1683. true = ets:delete(async_threshold_test),
  1684. error_logger:tty(true);
  1685. true ->
  1686. _ = (catch ets:delete(async_threshold_test)),
  1687. ok
  1688. end
  1689. end,
  1690. Setup = fun() ->
  1691. % Evidence suggests that previous tests somewhere are leaving some of this stuff
  1692. % loaded, and cleaning it out forcefully to allows the test to succeed.
  1693. _ = Cleanup(false),
  1694. _ = ets:new(async_threshold_test, [set, named_table, public]),
  1695. ?assertEqual(true, ets:insert_new(async_threshold_test, {sync_toggled, 0})),
  1696. ?assertEqual(true, ets:insert_new(async_threshold_test, {async_toggled, 0})),
  1697. _ = application:load(lager),
  1698. ok = application:set_env(lager, error_logger_redirect, false),
  1699. ok = application:set_env(lager, async_threshold, 2),
  1700. ok = application:set_env(lager, async_threshold_window, 1),
  1701. ok = application:set_env(lager, handlers, [{?MODULE, info}]),
  1702. ok = eRum:start(),
  1703. true
  1704. end,
  1705. {foreach, Setup, Cleanup, [
  1706. {"async threshold works",
  1707. {timeout, 30, fun() ->
  1708. Sleep = get_long_sleep_value(),
  1709. %% we start out async
  1710. ?assertEqual(true, lager_config:get(async)),
  1711. ?assertEqual([{sync_toggled, 0}],
  1712. ets:lookup(async_threshold_test, sync_toggled)),
  1713. %% put a ton of things in the queue
  1714. WorkCnt = erlang:max(10, (erlang:system_info(schedulers) * 2)),
  1715. OtpVsn = rumUtil:otp_version(),
  1716. % newer OTPs *may* handle the messages faster, so we'll send more
  1717. MsgCnt = ((OtpVsn * OtpVsn) div 2),
  1718. Workers = spawn_stuffers(WorkCnt, [MsgCnt, info, "hello world"], []),
  1719. %% serialize on mailbox
  1720. _ = gen_event:which_handlers(lager_event),
  1721. timer:sleep(Sleep),
  1722. %% By now the flood of messages should have forced the backend throttle
  1723. %% to turn off async mode, but it's possible all outstanding requests
  1724. %% have been processed, so checking the current status (sync or async)
  1725. %% is an exercise in race control.
  1726. %% Instead, we'll see whether the backend throttle has toggled into sync
  1727. %% mode at any point in the past.
  1728. ?assertMatch([{sync_toggled, N}] when N > 0,
  1729. ets:lookup(async_threshold_test, sync_toggled)),
  1730. %% Wait for all the workers to return, meaning that all the messages have
  1731. %% been logged (since we're definitely in sync mode at the end of the run).
  1732. collect_workers(Workers),
  1733. %% serialize on the mailbox again
  1734. _ = gen_event:which_handlers(lager_event),
  1735. timer:sleep(Sleep),
  1736. eRum:info("hello world"),
  1737. _ = gen_event:which_handlers(lager_event),
  1738. timer:sleep(Sleep),
  1739. %% async is true again now that the mailbox has drained
  1740. ?assertEqual(true, lager_config:get(async)),
  1741. ok
  1742. end}}
  1743. ]}.
  1744. % Fire off the stuffers with minimal resource overhead - speed is of the essence.
  1745. spawn_stuffers(0, _, Refs) ->
  1746. % Attempt to return them in about the order that they'll finish.
  1747. lists:reverse(Refs);
  1748. spawn_stuffers(N, Args, Refs) ->
  1749. {_Pid, Ref} = erlang:spawn_monitor(?MODULE, message_stuffer, Args),
  1750. spawn_stuffers((N - 1), Args, [Ref | Refs]).
  1751. % Spawned process to stuff N copies of Message into lager's message queue as fast as possible.
  1752. % Skip using a list function for speed and low memory footprint - don't want to take the
  1753. % resources to create a sequence (or pass one in).
  1754. message_stuffer(N, Level, Message) ->
  1755. message_stuffer_(N, Level, [{pid, erlang:self()}], Message).
  1756. message_stuffer_(0, _, _, _) ->
  1757. ok;
  1758. message_stuffer_(N, Level, Meta, Message) ->
  1759. eRum:log(Level, Meta, Message),
  1760. message_stuffer_((N - 1), Level, Meta, Message).
  1761. collect_workers([]) ->
  1762. ok;
  1763. collect_workers([Ref | Refs]) ->
  1764. receive
  1765. {'DOWN', Ref, _, _, _} ->
  1766. collect_workers(Refs)
  1767. end.
  1768. produce_n_error_logger_msgs(N) ->
  1769. lists:foreach(fun(K) ->
  1770. error_logger:error_msg("Foo ~p!", [K])
  1771. end,
  1772. lists:seq(0, N - 1)
  1773. ).
  1774. high_watermark_test_() ->
  1775. {foreach,
  1776. fun() ->
  1777. error_logger:tty(false),
  1778. application:load(lager),
  1779. application:set_env(lager, error_logger_redirect, true),
  1780. application:set_env(lager, handlers, [{lager_test_backend, info}]),
  1781. application:set_env(lager, async_threshold, undefined),
  1782. eRum:start()
  1783. end,
  1784. fun(_) ->
  1785. application:stop(lager),
  1786. error_logger:tty(true)
  1787. end,
  1788. [
  1789. {"Nothing dropped when error_logger high watermark is undefined",
  1790. fun() ->
  1791. ok = error_logger_lager_h:set_high_water(undefined),
  1792. timer:sleep(100),
  1793. produce_n_error_logger_msgs(10),
  1794. timer:sleep(500),
  1795. ?assert(count() >= 10)
  1796. end
  1797. },
  1798. {"Mostly dropped according to error_logger high watermark",
  1799. fun() ->
  1800. ok = error_logger_lager_h:set_high_water(5),
  1801. timer:sleep(100),
  1802. produce_n_error_logger_msgs(50),
  1803. timer:sleep(1000),
  1804. ?assert(count() < 20)
  1805. end
  1806. },
  1807. {"Non-notifications are not dropped",
  1808. fun() ->
  1809. ok = error_logger_lager_h:set_high_water(2),
  1810. timer:sleep(100),
  1811. spawn(fun() -> produce_n_error_logger_msgs(300) end),
  1812. timer:sleep(50),
  1813. %% if everything were dropped, this call would be dropped
  1814. %% too, so lets hope it's not
  1815. ?assert(is_integer(count())),
  1816. timer:sleep(1000),
  1817. ?assert(count() < 10)
  1818. end
  1819. }
  1820. ]
  1821. }.
  1822. get_long_sleep_value() ->
  1823. case os:getenv("CI") of
  1824. false ->
  1825. 500;
  1826. _ ->
  1827. 5000
  1828. end.
  1829. -endif.