You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1855 lines
95 KiB

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