Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

1080 righe
58 KiB

14 anni fa
14 anni fa
14 anni fa
14 anni fa
14 anni fa
14 anni fa
14 anni fa
14 anni fa
14 anni fa
  1. %% Copyright (c) 2011-2012 Basho Technologies, Inc. All Rights Reserved.
  2. %%
  3. %% This file is provided to you under the Apache License,
  4. %% Version 2.0 (the "License"); you may not use this file
  5. %% except in compliance with the License. You may obtain
  6. %% a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing,
  11. %% software distributed under the License is distributed on an
  12. %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. %% KIND, either express or implied. See the License for the
  14. %% specific language governing permissions and limitations
  15. %% under the License.
  16. -module(lager_test_backend).
  17. -include("lager.hrl").
  18. -behaviour(gen_event).
  19. -export([init/1, handle_call/2, handle_event/2, handle_info/2, terminate/2,
  20. code_change/3]).
  21. -record(state, {level, buffer, ignored}).
  22. -record(test, {attrs, format, args}).
  23. -compile([{parse_transform, lager_transform}]).
  24. -ifdef(TEST).
  25. -include_lib("eunit/include/eunit.hrl").
  26. -export([pop/0, count/0, count_ignored/0, flush/0, print_state/0]).
  27. -endif.
  28. init(Level) ->
  29. {ok, #state{level=lager_util:config_to_mask(Level), buffer=[], ignored=[]}}.
  30. handle_call(count, #state{buffer=Buffer} = State) ->
  31. {ok, length(Buffer), State};
  32. handle_call(count_ignored, #state{ignored=Ignored} = State) ->
  33. {ok, length(Ignored), State};
  34. handle_call(flush, State) ->
  35. {ok, ok, State#state{buffer=[], ignored=[]}};
  36. handle_call(pop, #state{buffer=Buffer} = State) ->
  37. case Buffer of
  38. [] ->
  39. {ok, undefined, State};
  40. [H|T] ->
  41. {ok, H, State#state{buffer=T}}
  42. end;
  43. handle_call(get_loglevel, #state{level=Level} = State) ->
  44. {ok, Level, State};
  45. handle_call({set_loglevel, Level}, State) ->
  46. {ok, ok, State#state{level=lager_util:config_to_mask(Level)}};
  47. handle_call(print_state, State) ->
  48. spawn(fun() -> lager:info("State ~p", [lager:pr(State, ?MODULE)]) end),
  49. timer:sleep(100),
  50. {ok, ok, State};
  51. handle_call(print_bad_state, State) ->
  52. spawn(fun() -> lager:info("State ~p", [lager:pr({state, 1}, ?MODULE)]) end),
  53. timer:sleep(100),
  54. {ok, ok, State};
  55. handle_call(_Request, State) ->
  56. {ok, ok, State}.
  57. handle_event({log, Msg},
  58. #state{level=LogLevel,buffer=Buffer,ignored=Ignored} = State) ->
  59. case lager_util:is_loggable(Msg, LogLevel, ?MODULE) of
  60. true ->
  61. {ok, State#state{buffer=Buffer ++
  62. [{lager_msg:severity_as_int(Msg),
  63. lager_msg:datetime(Msg),
  64. lager_msg:message(Msg), lager_msg:metadata(Msg)}]}};
  65. _ ->
  66. {ok, State#state{ignored=Ignored ++ [ignored]}}
  67. end;
  68. handle_event(_Event, State) ->
  69. {ok, State}.
  70. handle_info(_Info, State) ->
  71. {ok, State}.
  72. terminate(_Reason, _State) ->
  73. ok.
  74. code_change(_OldVsn, State, _Extra) ->
  75. {ok, State}.
  76. -ifdef(TEST).
  77. pop() ->
  78. gen_event:call(lager_event, ?MODULE, pop).
  79. count() ->
  80. gen_event:call(lager_event, ?MODULE, count).
  81. count_ignored() ->
  82. gen_event:call(lager_event, ?MODULE, count_ignored).
  83. flush() ->
  84. gen_event:call(lager_event, ?MODULE, flush).
  85. print_state() ->
  86. gen_event:call(lager_event, ?MODULE, print_state).
  87. print_bad_state() ->
  88. gen_event:call(lager_event, ?MODULE, print_bad_state).
  89. has_line_numbers() ->
  90. %% are we R15 or greater
  91. Rel = erlang:system_info(otp_release),
  92. {match, [Major]} = re:run(Rel, "^R(\\d+)[A|B](|0(\\d))$", [{capture, [1], list}]),
  93. list_to_integer(Major) >= 15.
  94. not_running_test() ->
  95. ?assertEqual({error, lager_not_running}, lager:log(info, self(), "not running")).
  96. lager_test_() ->
  97. {foreach,
  98. fun setup/0,
  99. fun cleanup/1,
  100. [
  101. {"observe that there is nothing up my sleeve",
  102. fun() ->
  103. ?assertEqual(undefined, pop()),
  104. ?assertEqual(0, count())
  105. end
  106. },
  107. {"logging works",
  108. fun() ->
  109. lager:warning("test message"),
  110. ?assertEqual(1, count()),
  111. {Level, _Time, Message, _Metadata} = pop(),
  112. ?assertMatch(Level, lager_util:level_to_num(warning)),
  113. ?assertEqual("test message", Message),
  114. ok
  115. end
  116. },
  117. {"logging with arguments works",
  118. fun() ->
  119. lager:warning("test message ~p", [self()]),
  120. ?assertEqual(1, count()),
  121. {Level, _Time, Message,_Metadata} = pop(),
  122. ?assertMatch(Level, lager_util:level_to_num(warning)),
  123. ?assertEqual(lists:flatten(io_lib:format("test message ~p", [self()])), lists:flatten(Message)),
  124. ok
  125. end
  126. },
  127. {"logging works from inside a begin/end block",
  128. fun() ->
  129. ?assertEqual(0, count()),
  130. begin
  131. lager:warning("test message 2")
  132. end,
  133. ?assertEqual(1, count()),
  134. ok
  135. end
  136. },
  137. {"logging works from inside a list comprehension",
  138. fun() ->
  139. ?assertEqual(0, count()),
  140. [lager:warning("test message") || _N <- lists:seq(1, 10)],
  141. ?assertEqual(10, count()),
  142. ok
  143. end
  144. },
  145. {"logging works from a begin/end block inside a list comprehension",
  146. fun() ->
  147. ?assertEqual(0, count()),
  148. [ begin lager:warning("test message") end || _N <- lists:seq(1, 10)],
  149. ?assertEqual(10, count()),
  150. ok
  151. end
  152. },
  153. {"logging works from a nested list comprehension",
  154. fun() ->
  155. ?assertEqual(0, count()),
  156. [ [lager:warning("test message") || _N <- lists:seq(1, 10)] ||
  157. _I <- lists:seq(1, 10)],
  158. ?assertEqual(100, count()),
  159. ok
  160. end
  161. },
  162. {"variables inplace of literals in logging statements work",
  163. fun() ->
  164. ?assertEqual(0, count()),
  165. Attr = [{a, alpha}, {b, beta}],
  166. Fmt = "format ~p",
  167. Args = [world],
  168. lager:info(Attr, "hello"),
  169. lager:info(Attr, "hello ~p", [world]),
  170. lager:info(Fmt, [world]),
  171. lager:info("hello ~p", Args),
  172. lager:info(Attr, "hello ~p", Args),
  173. lager:info([{d, delta}, {g, gamma}], Fmt, Args),
  174. ?assertEqual(6, count()),
  175. {_Level, _Time, Message, Metadata} = pop(),
  176. ?assertMatch([{a, alpha}, {b, beta}|_], Metadata),
  177. ?assertEqual("hello", lists:flatten(Message)),
  178. {_Level, _Time2, Message2, _Metadata2} = pop(),
  179. ?assertEqual("hello world", lists:flatten(Message2)),
  180. {_Level, _Time3, Message3, _Metadata3} = pop(),
  181. ?assertEqual("format world", lists:flatten(Message3)),
  182. {_Level, _Time4, Message4, _Metadata4} = pop(),
  183. ?assertEqual("hello world", lists:flatten(Message4)),
  184. {_Level, _Time5, Message5, _Metadata5} = pop(),
  185. ?assertEqual("hello world", lists:flatten(Message5)),
  186. {_Level, _Time6, Message6, Metadata6} = pop(),
  187. ?assertMatch([{d, delta}, {g, gamma}|_], Metadata6),
  188. ?assertEqual("format world", lists:flatten(Message6)),
  189. ok
  190. end
  191. },
  192. {"list comprehension inplace of literals in logging statements work",
  193. fun() ->
  194. ?assertEqual(0, count()),
  195. Attr = [{a, alpha}, {b, beta}],
  196. Fmt = "format ~p",
  197. Args = [world],
  198. lager:info([{K, atom_to_list(V)} || {K, V} <- Attr], "hello"),
  199. lager:info([{K, atom_to_list(V)} || {K, V} <- Attr], "hello ~p", [{atom, X} || X <- Args]),
  200. lager:info([X || X <- Fmt], [world]),
  201. lager:info("hello ~p", [{atom, X} || X <- Args]),
  202. lager:info([{K, atom_to_list(V)} || {K, V} <- Attr], "hello ~p", [{atom, X} || X <- Args]),
  203. lager:info([{d, delta}, {g, gamma}], Fmt, [{atom, X} || X <- Args]),
  204. ?assertEqual(6, count()),
  205. {_Level, _Time, Message, Metadata} = pop(),
  206. ?assertMatch([{a, "alpha"}, {b, "beta"}|_], Metadata),
  207. ?assertEqual("hello", lists:flatten(Message)),
  208. {_Level, _Time2, Message2, _Metadata2} = pop(),
  209. ?assertEqual("hello {atom,world}", lists:flatten(Message2)),
  210. {_Level, _Time3, Message3, _Metadata3} = pop(),
  211. ?assertEqual("format world", lists:flatten(Message3)),
  212. {_Level, _Time4, Message4, _Metadata4} = pop(),
  213. ?assertEqual("hello {atom,world}", lists:flatten(Message4)),
  214. {_Level, _Time5, Message5, _Metadata5} = pop(),
  215. ?assertEqual("hello {atom,world}", lists:flatten(Message5)),
  216. {_Level, _Time6, Message6, Metadata6} = pop(),
  217. ?assertMatch([{d, delta}, {g, gamma}|_], Metadata6),
  218. ?assertEqual("format {atom,world}", lists:flatten(Message6)),
  219. ok
  220. end
  221. },
  222. {"function calls inplace of literals in logging statements work",
  223. fun() ->
  224. ?assertEqual(0, count()),
  225. put(attrs, [{a, alpha}, {b, beta}]),
  226. put(format, "format ~p"),
  227. put(args, [world]),
  228. lager:info(get(attrs), "hello"),
  229. lager:info(get(attrs), "hello ~p", get(args)),
  230. lager:info(get(format), [world]),
  231. lager:info("hello ~p", erlang:get(args)),
  232. lager:info(fun() -> get(attrs) end(), "hello ~p", get(args)),
  233. lager:info([{d, delta}, {g, gamma}], get(format), get(args)),
  234. ?assertEqual(6, count()),
  235. {_Level, _Time, Message, Metadata} = pop(),
  236. ?assertMatch([{a, alpha}, {b, beta}|_], Metadata),
  237. ?assertEqual("hello", lists:flatten(Message)),
  238. {_Level, _Time2, Message2, _Metadata2} = pop(),
  239. ?assertEqual("hello world", lists:flatten(Message2)),
  240. {_Level, _Time3, Message3, _Metadata3} = pop(),
  241. ?assertEqual("format world", lists:flatten(Message3)),
  242. {_Level, _Time4, Message4, _Metadata4} = pop(),
  243. ?assertEqual("hello world", lists:flatten(Message4)),
  244. {_Level, _Time5, Message5, _Metadata5} = pop(),
  245. ?assertEqual("hello world", lists:flatten(Message5)),
  246. {_Level, _Time6, Message6, Metadata6} = pop(),
  247. ?assertMatch([{d, delta}, {g, gamma}|_], Metadata6),
  248. ?assertEqual("format world", lists:flatten(Message6)),
  249. ok
  250. end
  251. },
  252. {"record fields inplace of literals in logging statements work",
  253. fun() ->
  254. ?assertEqual(0, count()),
  255. Test = #test{attrs=[{a, alpha}, {b, beta}], format="format ~p", args=[world]},
  256. lager:info(Test#test.attrs, "hello"),
  257. lager:info(Test#test.attrs, "hello ~p", Test#test.args),
  258. lager:info(Test#test.format, [world]),
  259. lager:info("hello ~p", Test#test.args),
  260. lager:info(Test#test.attrs, "hello ~p", Test#test.args),
  261. lager:info([{d, delta}, {g, gamma}], Test#test.format, Test#test.args),
  262. ?assertEqual(6, count()),
  263. {_Level, _Time, Message, Metadata} = pop(),
  264. ?assertMatch([{a, alpha}, {b, beta}|_], Metadata),
  265. ?assertEqual("hello", lists:flatten(Message)),
  266. {_Level, _Time2, Message2, _Metadata2} = pop(),
  267. ?assertEqual("hello world", lists:flatten(Message2)),
  268. {_Level, _Time3, Message3, _Metadata3} = pop(),
  269. ?assertEqual("format world", lists:flatten(Message3)),
  270. {_Level, _Time4, Message4, _Metadata4} = pop(),
  271. ?assertEqual("hello world", lists:flatten(Message4)),
  272. {_Level, _Time5, Message5, _Metadata5} = pop(),
  273. ?assertEqual("hello world", lists:flatten(Message5)),
  274. {_Level, _Time6, Message6, Metadata6} = pop(),
  275. ?assertMatch([{d, delta}, {g, gamma}|_], Metadata6),
  276. ?assertEqual("format world", lists:flatten(Message6)),
  277. ok
  278. end
  279. },
  280. {"log messages below the threshold are ignored",
  281. fun() ->
  282. ?assertEqual(0, count()),
  283. lager:debug("this message will be ignored"),
  284. ?assertEqual(0, count()),
  285. ?assertEqual(0, count_ignored()),
  286. lager_config:set(loglevel, {element(2, lager_util:config_to_mask(debug)), []}),
  287. lager:debug("this message should be ignored"),
  288. ?assertEqual(0, count()),
  289. ?assertEqual(1, count_ignored()),
  290. lager:set_loglevel(?MODULE, debug),
  291. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  292. lager:debug("this message should be logged"),
  293. ?assertEqual(1, count()),
  294. ?assertEqual(1, count_ignored()),
  295. ?assertEqual(debug, lager:get_loglevel(?MODULE)),
  296. ok
  297. end
  298. },
  299. {"tracing works",
  300. fun() ->
  301. lager_config:set(loglevel, {element(2, lager_util:config_to_mask(error)), []}),
  302. ok = lager:info("hello world"),
  303. ?assertEqual(0, count()),
  304. lager:trace(?MODULE, [{module, ?MODULE}], debug),
  305. ?assertMatch({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, _}, lager_config:get(loglevel)),
  306. %% elegible for tracing
  307. ok = lager:info("hello world"),
  308. %% NOT elegible for tracing
  309. ok = lager:log(info, [{pid, self()}], "hello world"),
  310. ?assertEqual(1, count()),
  311. ok
  312. end
  313. },
  314. {"tracing works with custom attributes",
  315. fun() ->
  316. lager:set_loglevel(?MODULE, error),
  317. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  318. lager_config:set(loglevel, {element(2, lager_util:config_to_mask(error)), []}),
  319. lager:info([{requestid, 6}], "hello world"),
  320. ?assertEqual(0, count()),
  321. lager:trace(?MODULE, [{requestid, 6}, {foo, bar}], debug),
  322. lager:info([{requestid, 6}, {foo, bar}], "hello world"),
  323. ?assertEqual(1, count()),
  324. lager:trace(?MODULE, [{requestid, '*'}], debug),
  325. lager:info([{requestid, 6}], "hello world"),
  326. ?assertEqual(2, count()),
  327. lager:clear_all_traces(),
  328. lager:info([{requestid, 6}], "hello world"),
  329. ?assertEqual(2, count()),
  330. ok
  331. end
  332. },
  333. {"tracing honors loglevel",
  334. fun() ->
  335. lager:set_loglevel(?MODULE, error),
  336. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  337. {ok, T} = lager:trace(?MODULE, [{module, ?MODULE}], notice),
  338. ok = lager:info("hello world"),
  339. ?assertEqual(0, count()),
  340. ok = lager:notice("hello world"),
  341. ?assertEqual(1, count()),
  342. lager:stop_trace(T),
  343. ok = lager:notice("hello world"),
  344. ?assertEqual(1, count()),
  345. ok
  346. end
  347. },
  348. {"record printing works",
  349. fun() ->
  350. print_state(),
  351. {Level, _Time, Message, _Metadata} = pop(),
  352. ?assertMatch(Level, lager_util:level_to_num(info)),
  353. {mask, Mask} = lager_util:config_to_mask(info),
  354. ?assertEqual("State #state{level={mask,"++integer_to_list(Mask)++"},buffer=[],ignored=[]}", lists:flatten(Message)),
  355. ok
  356. end
  357. },
  358. {"record printing fails gracefully",
  359. fun() ->
  360. print_bad_state(),
  361. {Level, _Time, Message, _Metadata} = pop(),
  362. ?assertMatch(Level, lager_util:level_to_num(info)),
  363. ?assertEqual("State {state,1}", lists:flatten(Message)),
  364. ok
  365. end
  366. },
  367. {"record printing fails gracefully when no lager_record attribute",
  368. fun() ->
  369. spawn(fun() -> lager:info("State ~p", [lager:pr({state, 1}, lager)]) end),
  370. timer:sleep(100),
  371. {Level, _Time, Message, _Metadata} = pop(),
  372. ?assertMatch(Level, lager_util:level_to_num(info)),
  373. ?assertEqual("State {state,1}", lists:flatten(Message)),
  374. ok
  375. end
  376. },
  377. {"record printing fails gracefully when input is not a tuple",
  378. fun() ->
  379. spawn(fun() -> lager:info("State ~p", [lager:pr(ok, lager)]) end),
  380. timer:sleep(100),
  381. {Level, _Time, Message, _Metadata} = pop(),
  382. ?assertMatch(Level, lager_util:level_to_num(info)),
  383. ?assertEqual("State ok", lists:flatten(Message)),
  384. ok
  385. end
  386. },
  387. {"record printing fails gracefully when module is invalid",
  388. fun() ->
  389. spawn(fun() -> lager:info("State ~p", [lager:pr({state, 1}, not_a_module)]) end),
  390. timer:sleep(100),
  391. {Level, _Time, Message, _Metadata} = pop(),
  392. ?assertMatch(Level, lager_util:level_to_num(info)),
  393. ?assertEqual("State {state,1}", lists:flatten(Message)),
  394. ok
  395. end
  396. },
  397. {"installing a new handler adjusts the global loglevel if necessary",
  398. fun() ->
  399. ?assertEqual({?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  400. supervisor:start_child(lager_handler_watcher_sup, [lager_event, {?MODULE, foo}, debug]),
  401. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  402. ok
  403. end
  404. }
  405. ]
  406. }.
  407. setup() ->
  408. error_logger:tty(false),
  409. application:load(lager),
  410. application:set_env(lager, handlers, [{?MODULE, info}]),
  411. application:set_env(lager, error_logger_redirect, false),
  412. application:start(lager),
  413. gen_event:call(lager_event, ?MODULE, flush).
  414. cleanup(_) ->
  415. application:stop(lager),
  416. error_logger:tty(true).
  417. crash(Type) ->
  418. spawn(fun() -> gen_server:call(crash, Type) end),
  419. timer:sleep(100),
  420. _ = gen_event:which_handlers(error_logger),
  421. ok.
  422. test_body(Expected, Actual) ->
  423. case has_line_numbers() of
  424. true ->
  425. FileLine = string:substr(Actual, length(Expected)+1),
  426. Body = string:substr(Actual, 1, length(Expected)),
  427. ?assertEqual(Expected, Body),
  428. case string:substr(FileLine, 1, 6) of
  429. [] ->
  430. %% sometimes there's no line information...
  431. ?assert(true);
  432. " line " ->
  433. ?assert(true);
  434. Other ->
  435. ?debugFmt("unexpected trailing data ~p", [Other]),
  436. ?assert(false)
  437. end;
  438. false ->
  439. ?assertEqual(Expected, Actual)
  440. end.
  441. error_logger_redirect_crash_test_() ->
  442. TestBody=fun(Name,CrashReason,Expected) -> {Name,
  443. fun() ->
  444. Pid = whereis(crash),
  445. crash(CrashReason),
  446. {Level, _, Msg,Metadata} = pop(),
  447. test_body(Expected, lists:flatten(Msg)),
  448. ?assertEqual(Pid,proplists:get_value(pid,Metadata)),
  449. ?assertEqual(lager_util:level_to_num(error),Level)
  450. end
  451. }
  452. end,
  453. {foreach,
  454. fun() ->
  455. error_logger:tty(false),
  456. application:load(lager),
  457. application:set_env(lager, error_logger_redirect, true),
  458. application:set_env(lager, handlers, [{?MODULE, error}]),
  459. application:start(lager),
  460. crash:start()
  461. end,
  462. fun(_) ->
  463. application:stop(lager),
  464. case whereis(crash) of
  465. undefined -> ok;
  466. Pid -> exit(Pid, kill)
  467. end,
  468. error_logger:tty(true)
  469. end,
  470. [
  471. {"again, there is nothing up my sleeve",
  472. fun() ->
  473. ?assertEqual(undefined, pop()),
  474. ?assertEqual(0, count())
  475. end
  476. },
  477. TestBody("bad return value",bad_return,"gen_server crash terminated with reason: bad return value: bleh"),
  478. TestBody("bad return value with string",bad_return_string,"gen_server crash terminated with reason: bad return value: {tuple,{tuple,\"string\"}}"),
  479. TestBody("bad return uncaught throw",throw,"gen_server crash terminated with reason: bad return value: a_ball"),
  480. TestBody("case clause",case_clause,"gen_server crash terminated with reason: no case clause matching {} in crash:handle_call/3"),
  481. TestBody("case clause string",case_clause_string,"gen_server crash terminated with reason: no case clause matching \"crash\" in crash:handle_call/3"),
  482. TestBody("function clause",function_clause,"gen_server crash terminated with reason: no function clause matching crash:function({})"),
  483. TestBody("if clause",if_clause,"gen_server crash terminated with reason: no true branch found while evaluating if expression in crash:handle_call/3"),
  484. TestBody("try clause",try_clause,"gen_server crash terminated with reason: no try clause matching [] in crash:handle_call/3"),
  485. TestBody("undefined function",undef,"gen_server crash terminated with reason: call to undefined function crash:booger/0 from crash:handle_call/3"),
  486. TestBody("bad math",badarith,"gen_server crash terminated with reason: bad arithmetic expression in crash:handle_call/3"),
  487. TestBody("bad match",badmatch,"gen_server crash terminated with reason: no match of right hand value {} in crash:handle_call/3"),
  488. 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"),
  489. TestBody("bad arg1",badarg1,"gen_server crash terminated with reason: bad argument in crash:handle_call/3"),
  490. 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"),
  491. TestBody("bad record",badrecord,"gen_server crash terminated with reason: bad record state in crash:handle_call/3"),
  492. TestBody("noproc",noproc,"gen_server crash terminated with reason: no such process or port in call to gen_event:call(foo, bar, baz)"),
  493. TestBody("badfun",badfun,"gen_server crash terminated with reason: bad function booger in crash:handle_call/3")
  494. ]
  495. }.
  496. error_logger_redirect_test_() ->
  497. {foreach,
  498. fun() ->
  499. error_logger:tty(false),
  500. application:load(lager),
  501. application:set_env(lager, error_logger_redirect, true),
  502. application:set_env(lager, handlers, [{?MODULE, info}]),
  503. application:start(lager),
  504. lager:log(error, self(), "flush flush"),
  505. timer:sleep(100),
  506. gen_event:call(lager_event, ?MODULE, flush)
  507. end,
  508. fun(_) ->
  509. application:stop(lager),
  510. error_logger:tty(true)
  511. end,
  512. [
  513. {"error reports are printed",
  514. fun() ->
  515. sync_error_logger:error_report([{this, is}, a, {silly, format}]),
  516. _ = gen_event:which_handlers(error_logger),
  517. {Level, _, Msg,Metadata} = pop(),
  518. ?assertEqual(lager_util:level_to_num(error),Level),
  519. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  520. Expected = "this: is, a, silly: format",
  521. ?assertEqual(Expected, lists:flatten(Msg))
  522. end
  523. },
  524. {"string error reports are printed",
  525. fun() ->
  526. sync_error_logger:error_report("this is less silly"),
  527. _ = gen_event:which_handlers(error_logger),
  528. {Level, _, Msg,Metadata} = pop(),
  529. ?assertEqual(lager_util:level_to_num(error),Level),
  530. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  531. Expected = "this is less silly",
  532. ?assertEqual(Expected, lists:flatten(Msg))
  533. end
  534. },
  535. {"error messages are printed",
  536. fun() ->
  537. sync_error_logger:error_msg("doom, doom has come upon you all"),
  538. _ = gen_event:which_handlers(error_logger),
  539. {Level, _, Msg,Metadata} = pop(),
  540. ?assertEqual(lager_util:level_to_num(error),Level),
  541. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  542. Expected = "doom, doom has come upon you all",
  543. ?assertEqual(Expected, lists:flatten(Msg))
  544. end
  545. },
  546. {"error messages are truncated at 4096 characters",
  547. fun() ->
  548. sync_error_logger:error_msg("doom, doom has come upon you all ~p", [string:copies("doom", 10000)]),
  549. _ = gen_event:which_handlers(error_logger),
  550. {_, _, Msg,_Metadata} = pop(),
  551. ?assert(length(lists:flatten(Msg)) < 5100)
  552. end
  553. },
  554. {"info reports are printed",
  555. fun() ->
  556. sync_error_logger:info_report([{this, is}, a, {silly, format}]),
  557. _ = gen_event:which_handlers(error_logger),
  558. {Level, _, Msg,Metadata} = pop(),
  559. ?assertEqual(lager_util:level_to_num(info),Level),
  560. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  561. Expected = "this: is, a, silly: format",
  562. ?assertEqual(Expected, lists:flatten(Msg))
  563. end
  564. },
  565. {"info reports are truncated at 4096 characters",
  566. fun() ->
  567. sync_error_logger:info_report([[{this, is}, a, {silly, format}] || _ <- lists:seq(0, 600)]),
  568. _ = gen_event:which_handlers(error_logger),
  569. {Level, _, Msg,Metadata} = pop(),
  570. ?assertEqual(lager_util:level_to_num(info),Level),
  571. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  572. ?assert(length(lists:flatten(Msg)) < 5000)
  573. end
  574. },
  575. {"single term info reports are printed",
  576. fun() ->
  577. sync_error_logger:info_report({foolish, bees}),
  578. _ = gen_event:which_handlers(error_logger),
  579. {Level, _, Msg,Metadata} = pop(),
  580. ?assertEqual(lager_util:level_to_num(info),Level),
  581. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  582. ?assertEqual("{foolish,bees}", lists:flatten(Msg))
  583. end
  584. },
  585. {"single term error reports are printed",
  586. fun() ->
  587. sync_error_logger:error_report({foolish, bees}),
  588. _ = gen_event:which_handlers(error_logger),
  589. {Level, _, Msg,Metadata} = pop(),
  590. ?assertEqual(lager_util:level_to_num(error),Level),
  591. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  592. ?assertEqual("{foolish,bees}", lists:flatten(Msg))
  593. end
  594. },
  595. {"string info reports are printed",
  596. fun() ->
  597. sync_error_logger:info_report("this is less silly"),
  598. _ = gen_event:which_handlers(error_logger),
  599. {Level, _, Msg,Metadata} = pop(),
  600. ?assertEqual(lager_util:level_to_num(info),Level),
  601. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  602. ?assertEqual("this is less silly", lists:flatten(Msg))
  603. end
  604. },
  605. {"string info reports are truncated at 4096 characters",
  606. fun() ->
  607. sync_error_logger:info_report(string:copies("this is less silly", 1000)),
  608. _ = gen_event:which_handlers(error_logger),
  609. {Level, _, Msg,Metadata} = pop(),
  610. ?assertEqual(lager_util:level_to_num(info),Level),
  611. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  612. ?assert(length(lists:flatten(Msg)) < 5100)
  613. end
  614. },
  615. {"strings in a mixed report are printed as strings",
  616. fun() ->
  617. sync_error_logger:info_report(["this is less silly", {than, "this"}]),
  618. _ = gen_event:which_handlers(error_logger),
  619. {Level, _, Msg,Metadata} = pop(),
  620. ?assertEqual(lager_util:level_to_num(info),Level),
  621. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  622. ?assertEqual("\"this is less silly\", than: \"this\"", lists:flatten(Msg))
  623. end
  624. },
  625. {"info messages are printed",
  626. fun() ->
  627. sync_error_logger:info_msg("doom, doom has come upon you all"),
  628. _ = gen_event:which_handlers(error_logger),
  629. {Level, _, Msg,Metadata} = pop(),
  630. ?assertEqual(lager_util:level_to_num(info),Level),
  631. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  632. ?assertEqual("doom, doom has come upon you all", lists:flatten(Msg))
  633. end
  634. },
  635. {"info messages are truncated at 4096 characters",
  636. fun() ->
  637. sync_error_logger:info_msg("doom, doom has come upon you all ~p", [string:copies("doom", 10000)]),
  638. _ = gen_event:which_handlers(error_logger),
  639. {Level, _, Msg,Metadata} = pop(),
  640. ?assertEqual(lager_util:level_to_num(info),Level),
  641. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  642. ?assert(length(lists:flatten(Msg)) < 5100)
  643. end
  644. },
  645. {"warning messages are printed at the correct level",
  646. fun() ->
  647. sync_error_logger:warning_msg("doom, doom has come upon you all"),
  648. Map = error_logger:warning_map(),
  649. _ = gen_event:which_handlers(error_logger),
  650. {Level, _, Msg,Metadata} = pop(),
  651. ?assertEqual(lager_util:level_to_num(Map),Level),
  652. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  653. ?assertEqual("doom, doom has come upon you all", lists:flatten(Msg))
  654. end
  655. },
  656. {"warning reports are printed at the correct level",
  657. fun() ->
  658. sync_error_logger:warning_report([{i, like}, pie]),
  659. Map = error_logger:warning_map(),
  660. _ = gen_event:which_handlers(error_logger),
  661. {Level, _, Msg,Metadata} = pop(),
  662. ?assertEqual(lager_util:level_to_num(Map),Level),
  663. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  664. ?assertEqual("i: like, pie", lists:flatten(Msg))
  665. end
  666. },
  667. {"single term warning reports are printed at the correct level",
  668. fun() ->
  669. sync_error_logger:warning_report({foolish, bees}),
  670. Map = error_logger:warning_map(),
  671. _ = gen_event:which_handlers(error_logger),
  672. {Level, _, Msg,Metadata} = pop(),
  673. ?assertEqual(lager_util:level_to_num(Map),Level),
  674. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  675. ?assertEqual("{foolish,bees}", lists:flatten(Msg))
  676. end
  677. },
  678. {"application stop reports",
  679. fun() ->
  680. sync_error_logger:info_report([{application, foo}, {exited, quittin_time}, {type, lazy}]),
  681. _ = gen_event:which_handlers(error_logger),
  682. {Level, _, Msg,Metadata} = pop(),
  683. ?assertEqual(lager_util:level_to_num(info),Level),
  684. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  685. ?assertEqual("Application foo exited with reason: quittin_time", lists:flatten(Msg))
  686. end
  687. },
  688. {"supervisor reports",
  689. fun() ->
  690. sync_error_logger:error_report(supervisor_report, [{errorContext, france}, {offender, [{name, mini_steve}, {mfargs, {a, b, [c]}}, {pid, bleh}]}, {reason, fired}, {supervisor, {local, steve}}]),
  691. _ = gen_event:which_handlers(error_logger),
  692. {Level, _, Msg,Metadata} = pop(),
  693. ?assertEqual(lager_util:level_to_num(error),Level),
  694. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  695. ?assertEqual("Supervisor steve had child mini_steve started with a:b(c) at bleh exit with reason fired in context france", lists:flatten(Msg))
  696. end
  697. },
  698. {"supervisor reports with real error",
  699. fun() ->
  700. 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}}]),
  701. _ = gen_event:which_handlers(error_logger),
  702. {Level, _, Msg,Metadata} = pop(),
  703. ?assertEqual(lager_util:level_to_num(error),Level),
  704. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  705. ?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))
  706. end
  707. },
  708. {"supervisor reports with real error and pid",
  709. fun() ->
  710. 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}]),
  711. _ = gen_event:which_handlers(error_logger),
  712. {Level, _, Msg,Metadata} = pop(),
  713. ?assertEqual(lager_util:level_to_num(error),Level),
  714. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  715. ?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))
  716. end
  717. },
  718. {"supervisor_bridge reports",
  719. fun() ->
  720. sync_error_logger:error_report(supervisor_report, [{errorContext, france}, {offender, [{mod, mini_steve}, {pid, bleh}]}, {reason, fired}, {supervisor, {local, steve}}]),
  721. _ = gen_event:which_handlers(error_logger),
  722. {Level, _, Msg,Metadata} = pop(),
  723. ?assertEqual(lager_util:level_to_num(error),Level),
  724. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  725. ?assertEqual("Supervisor steve had child at module mini_steve at bleh exit with reason fired in context france", lists:flatten(Msg))
  726. end
  727. },
  728. {"application progress report",
  729. fun() ->
  730. sync_error_logger:info_report(progress, [{application, foo}, {started_at, node()}]),
  731. _ = gen_event:which_handlers(error_logger),
  732. {Level, _, Msg,Metadata} = pop(),
  733. ?assertEqual(lager_util:level_to_num(info),Level),
  734. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  735. Expected = lists:flatten(io_lib:format("Application foo started on node ~w", [node()])),
  736. ?assertEqual(Expected, lists:flatten(Msg))
  737. end
  738. },
  739. {"supervisor progress report",
  740. fun() ->
  741. lager:set_loglevel(?MODULE, debug),
  742. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  743. sync_error_logger:info_report(progress, [{supervisor, {local, foo}}, {started, [{mfargs, {foo, bar, 1}}, {pid, baz}]}]),
  744. _ = gen_event:which_handlers(error_logger),
  745. {Level, _, Msg,Metadata} = pop(),
  746. ?assertEqual(lager_util:level_to_num(debug),Level),
  747. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  748. ?assertEqual("Supervisor foo started foo:bar/1 at pid baz", lists:flatten(Msg))
  749. end
  750. },
  751. {"supervisor progress report with pid",
  752. fun() ->
  753. lager:set_loglevel(?MODULE, debug),
  754. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  755. sync_error_logger:info_report(progress, [{supervisor, somepid}, {started, [{mfargs, {foo, bar, 1}}, {pid, baz}]}]),
  756. _ = gen_event:which_handlers(error_logger),
  757. {Level, _, Msg,Metadata} = pop(),
  758. ?assertEqual(lager_util:level_to_num(debug),Level),
  759. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  760. ?assertEqual("Supervisor somepid started foo:bar/1 at pid baz", lists:flatten(Msg))
  761. end
  762. },
  763. {"crash report for emfile",
  764. fun() ->
  765. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, emfile, [{stack, trace, 1}]}}], []]),
  766. _ = gen_event:which_handlers(error_logger),
  767. {Level, _, Msg,Metadata} = pop(),
  768. ?assertEqual(lager_util:level_to_num(error),Level),
  769. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  770. 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()])),
  771. ?assertEqual(Expected, lists:flatten(Msg))
  772. end
  773. },
  774. {"crash report for system process limit",
  775. fun() ->
  776. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, spawn, 1}]}}], []]),
  777. _ = gen_event:which_handlers(error_logger),
  778. {Level, _, Msg,Metadata} = pop(),
  779. ?assertEqual(lager_util:level_to_num(error),Level),
  780. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  781. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: maximum number of processes exceeded", [self()])),
  782. ?assertEqual(Expected, lists:flatten(Msg))
  783. end
  784. },
  785. {"crash report for system process limit2",
  786. fun() ->
  787. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, spawn_opt, 1}]}}], []]),
  788. _ = gen_event:which_handlers(error_logger),
  789. {Level, _, Msg,Metadata} = pop(),
  790. ?assertEqual(lager_util:level_to_num(error),Level),
  791. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  792. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: maximum number of processes exceeded", [self()])),
  793. ?assertEqual(Expected, lists:flatten(Msg))
  794. end
  795. },
  796. {"crash report for system port limit",
  797. fun() ->
  798. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, open_port, 1}]}}], []]),
  799. _ = gen_event:which_handlers(error_logger),
  800. {Level, _, Msg,Metadata} = pop(),
  801. ?assertEqual(lager_util:level_to_num(error),Level),
  802. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  803. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: maximum number of ports exceeded", [self()])),
  804. ?assertEqual(Expected, lists:flatten(Msg))
  805. end
  806. },
  807. {"crash report for system port limit",
  808. fun() ->
  809. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, list_to_atom, 1}]}}], []]),
  810. _ = gen_event:which_handlers(error_logger),
  811. {Level, _, Msg,Metadata} = pop(),
  812. ?assertEqual(lager_util:level_to_num(error),Level),
  813. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  814. 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()])),
  815. ?assertEqual(Expected, lists:flatten(Msg))
  816. end
  817. },
  818. {"crash report for system ets table limit",
  819. fun() ->
  820. 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}]}}], []]),
  821. _ = gen_event:which_handlers(error_logger),
  822. {Level, _, Msg,Metadata} = pop(),
  823. ?assertEqual(lager_util:level_to_num(error),Level),
  824. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  825. 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])),
  826. ?assertEqual(Expected, lists:flatten(Msg))
  827. end
  828. },
  829. {"crash report for unknown system limit should be truncated at 500 characters",
  830. fun() ->
  831. sync_error_logger:error_report(crash_report, [[{pid, self()}, {error_info, {error, system_limit, [{wtf,boom,[string:copies("aaaa", 4096)]}]}}], []]),
  832. _ = gen_event:which_handlers(error_logger),
  833. {_, _, Msg,_Metadata} = pop(),
  834. ?assert(length(lists:flatten(Msg)) > 550),
  835. ?assert(length(lists:flatten(Msg)) < 600)
  836. end
  837. },
  838. {"crash reports for 'special processes' should be handled right - function_clause",
  839. fun() ->
  840. {ok, Pid} = special_process:start(),
  841. unlink(Pid),
  842. Pid ! function_clause,
  843. timer:sleep(500),
  844. _ = gen_event:which_handlers(error_logger),
  845. {_, _, Msg, _Metadata} = pop(),
  846. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~p with 0 neighbours crashed with reason: no function clause matching special_process:foo(bar)",
  847. [Pid])),
  848. test_body(Expected, lists:flatten(Msg))
  849. end
  850. },
  851. {"crash reports for 'special processes' should be handled right - case_clause",
  852. fun() ->
  853. {ok, Pid} = special_process:start(),
  854. unlink(Pid),
  855. Pid ! {case_clause, wtf},
  856. timer:sleep(500),
  857. _ = gen_event:which_handlers(error_logger),
  858. {_, _, Msg, _Metadata} = pop(),
  859. 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",
  860. [Pid])),
  861. test_body(Expected, lists:flatten(Msg))
  862. end
  863. },
  864. {"crash reports for 'special processes' should be handled right - exit",
  865. fun() ->
  866. {ok, Pid} = special_process:start(),
  867. unlink(Pid),
  868. Pid ! exit,
  869. timer:sleep(500),
  870. _ = gen_event:which_handlers(error_logger),
  871. {_, _, Msg, _Metadata} = pop(),
  872. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~p with 0 neighbours exited with reason: byebye in special_process:loop/0",
  873. [Pid])),
  874. test_body(Expected, lists:flatten(Msg))
  875. end
  876. },
  877. {"crash reports for 'special processes' should be handled right - error",
  878. fun() ->
  879. {ok, Pid} = special_process:start(),
  880. unlink(Pid),
  881. Pid ! error,
  882. timer:sleep(500),
  883. _ = gen_event:which_handlers(error_logger),
  884. {_, _, Msg, _Metadata} = pop(),
  885. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~p with 0 neighbours crashed with reason: mybad in special_process:loop/0",
  886. [Pid])),
  887. test_body(Expected, lists:flatten(Msg))
  888. end
  889. },
  890. {"webmachine error reports",
  891. fun() ->
  892. Path = "/cgi-bin/phpmyadmin",
  893. Reason = {error,{error,{badmatch,{error,timeout}},
  894. [{myapp,dostuff,2,[{file,"src/myapp.erl"},{line,123}]},
  895. {webmachine_resource,resource_call,3,[{file,"src/webmachine_resource.erl"},{line,169}]}]}},
  896. sync_error_logger:error_msg("webmachine error: path=~p~n~p~n", [Path, Reason]),
  897. _ = gen_event:which_handlers(error_logger),
  898. {Level, _, Msg,Metadata} = pop(),
  899. ?assertEqual(lager_util:level_to_num(error),Level),
  900. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  901. ?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))
  902. end
  903. },
  904. {"Cowboy error reports, 8 arg version",
  905. fun() ->
  906. Stack = [{my_handler,init, 3,[{file,"src/my_handler.erl"},{line,123}]},
  907. {cowboy_handler,handler_init,4,[{file,"src/cowboy_handler.erl"},{line,169}]}],
  908. sync_error_logger:error_msg(
  909. "** Cowboy handler ~p terminating in ~p/~p~n"
  910. " for the reason ~p:~p~n"
  911. "** Options were ~p~n"
  912. "** Request was ~p~n"
  913. "** Stacktrace: ~p~n~n",
  914. [my_handler, init, 3, error, {badmatch, {error, timeout}}, [],
  915. "Request", Stack]),
  916. _ = gen_event:which_handlers(error_logger),
  917. {Level, _, Msg,Metadata} = pop(),
  918. ?assertEqual(lager_util:level_to_num(error),Level),
  919. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  920. ?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))
  921. end
  922. },
  923. {"Cowboy error reports, 10 arg version",
  924. fun() ->
  925. Stack = [{my_handler,somecallback, 3,[{file,"src/my_handler.erl"},{line,123}]},
  926. {cowboy_handler,handler_init,4,[{file,"src/cowboy_handler.erl"},{line,169}]}],
  927. sync_error_logger:error_msg(
  928. "** Cowboy handler ~p terminating in ~p/~p~n"
  929. " for the reason ~p:~p~n** Message was ~p~n"
  930. "** Options were ~p~n** Handler state was ~p~n"
  931. "** Request was ~p~n** Stacktrace: ~p~n~n",
  932. [my_handler, somecallback, 3, error, {badmatch, {error, timeout}}, hello, [],
  933. {}, "Request", Stack]),
  934. _ = gen_event:which_handlers(error_logger),
  935. {Level, _, Msg,Metadata} = pop(),
  936. ?assertEqual(lager_util:level_to_num(error),Level),
  937. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  938. ?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))
  939. end
  940. },
  941. {"Cowboy error reports, 5 arg version",
  942. fun() ->
  943. sync_error_logger:error_msg(
  944. "** Cowboy handler ~p terminating; "
  945. "function ~p/~p was not exported~n"
  946. "** Request was ~p~n** State was ~p~n~n",
  947. [my_handler, to_json, 2, "Request", {}]),
  948. _ = gen_event:which_handlers(error_logger),
  949. {Level, _, Msg,Metadata} = pop(),
  950. ?assertEqual(lager_util:level_to_num(error),Level),
  951. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  952. ?assertEqual("Cowboy handler my_handler terminated with reason: call to undefined function my_handler:to_json/2", lists:flatten(Msg))
  953. end
  954. },
  955. {"messages should not be generated if they don't satisfy the threshold",
  956. fun() ->
  957. lager:set_loglevel(?MODULE, error),
  958. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  959. sync_error_logger:info_report([hello, world]),
  960. _ = gen_event:which_handlers(error_logger),
  961. ?assertEqual(0, count()),
  962. ?assertEqual(0, count_ignored()),
  963. lager:set_loglevel(?MODULE, info),
  964. ?assertEqual({?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  965. sync_error_logger:info_report([hello, world]),
  966. _ = gen_event:which_handlers(error_logger),
  967. ?assertEqual(1, count()),
  968. ?assertEqual(0, count_ignored()),
  969. lager:set_loglevel(?MODULE, error),
  970. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  971. lager_config:set(loglevel, {element(2, lager_util:config_to_mask(debug)), []}),
  972. sync_error_logger:info_report([hello, world]),
  973. _ = gen_event:which_handlers(error_logger),
  974. ?assertEqual(1, count()),
  975. ?assertEqual(1, count_ignored())
  976. end
  977. }
  978. ]
  979. }.
  980. safe_format_test() ->
  981. ?assertEqual("foo bar", lists:flatten(lager:safe_format("~p ~p", [foo, bar], 1024))),
  982. ?assertEqual("FORMAT ERROR: \"~p ~p ~p\" [foo,bar]", lists:flatten(lager:safe_format("~p ~p ~p", [foo, bar], 1024))),
  983. ok.
  984. async_threshold_test_() ->
  985. {foreach,
  986. fun() ->
  987. error_logger:tty(false),
  988. application:load(lager),
  989. application:set_env(lager, error_logger_redirect, false),
  990. application:set_env(lager, async_threshold, 10),
  991. application:set_env(lager, handlers, [{?MODULE, info}]),
  992. application:start(lager)
  993. end,
  994. fun(_) ->
  995. application:unset_env(lager, async_threshold),
  996. application:stop(lager),
  997. error_logger:tty(true)
  998. end,
  999. [
  1000. {"async threshold works",
  1001. fun() ->
  1002. %% we start out async
  1003. ?assertEqual(true, lager_config:get(async)),
  1004. %% put a ton of things in the queue
  1005. Workers = [spawn_monitor(fun() -> [lager:info("hello world") || _ <- lists:seq(1, 1000)] end) || _ <- lists:seq(1, 10)],
  1006. %% serialize on mailbox
  1007. _ = gen_event:which_handlers(lager_event),
  1008. %% there should be a ton of outstanding messages now, so async is false
  1009. ?assertEqual(false, lager_config:get(async)),
  1010. %% wait for all the workers to return, meaning that all the messages have been logged (since we're in sync mode)
  1011. collect_workers(Workers),
  1012. %% serialize ont the mailbox again
  1013. _ = gen_event:which_handlers(lager_event),
  1014. %% just in case...
  1015. timer:sleep(100),
  1016. %% async is true again now that the mailbox has drained
  1017. ?assertEqual(true, lager_config:get(async)),
  1018. ok
  1019. end
  1020. }
  1021. ]
  1022. }.
  1023. collect_workers([]) ->
  1024. ok;
  1025. collect_workers(Workers) ->
  1026. receive
  1027. {'DOWN', Ref, _, _, _} ->
  1028. collect_workers(lists:keydelete(Ref, 2, Workers))
  1029. end.
  1030. -endif.