Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1832 строки
93 KiB

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