您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1107 行
60 KiB

14 年前
14 年前
14 年前
14 年前
14 年前
14 年前
14 年前
14 年前
14 年前
  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. {"metadata in the process dictionary works",
  406. fun() ->
  407. lager:md([{platypus, gravid}, {sloth, hirsute}, {duck, erroneous}]),
  408. lager:info("I sing the animal kingdom electric!"),
  409. {_Level, _Time, _Message, Metadata} = pop(),
  410. ?assertEqual(gravid, proplists:get_value(platypus, Metadata)),
  411. ?assertEqual(hirsute, proplists:get_value(sloth, Metadata)),
  412. ?assertEqual(erroneous, proplists:get_value(duck, Metadata)),
  413. ?assertEqual(undefined, proplists:get_value(eagle, Metadata)),
  414. lager:md([{platypus, gravid}, {sloth, hirsute}, {eagle, superincumbent}]),
  415. lager:info("I sing the animal kingdom dielectric!"),
  416. {_Level2, _Time2, _Message2, Metadata2} = pop(),
  417. ?assertEqual(gravid, proplists:get_value(platypus, Metadata2)),
  418. ?assertEqual(hirsute, proplists:get_value(sloth, Metadata2)),
  419. ?assertEqual(undefined, proplists:get_value(duck, Metadata2)),
  420. ?assertEqual(superincumbent, proplists:get_value(eagle, Metadata2)),
  421. ok
  422. end
  423. },
  424. {"can't store invalid metadata",
  425. fun() ->
  426. ?assertEqual(ok, lager:md([{platypus, gravid}, {sloth, hirsute}, {duck, erroneous}])),
  427. ?assertError(badarg, lager:md({flamboyant, flamingo})),
  428. ?assertError(badarg, lager:md("zookeeper zephyr")),
  429. ok
  430. end
  431. }
  432. ]
  433. }.
  434. setup() ->
  435. error_logger:tty(false),
  436. application:load(lager),
  437. application:set_env(lager, handlers, [{?MODULE, info}]),
  438. application:set_env(lager, error_logger_redirect, false),
  439. application:start(lager),
  440. gen_event:call(lager_event, ?MODULE, flush).
  441. cleanup(_) ->
  442. application:stop(lager),
  443. error_logger:tty(true).
  444. crash(Type) ->
  445. spawn(fun() -> gen_server:call(crash, Type) end),
  446. timer:sleep(100),
  447. _ = gen_event:which_handlers(error_logger),
  448. ok.
  449. test_body(Expected, Actual) ->
  450. case has_line_numbers() of
  451. true ->
  452. FileLine = string:substr(Actual, length(Expected)+1),
  453. Body = string:substr(Actual, 1, length(Expected)),
  454. ?assertEqual(Expected, Body),
  455. case string:substr(FileLine, 1, 6) of
  456. [] ->
  457. %% sometimes there's no line information...
  458. ?assert(true);
  459. " line " ->
  460. ?assert(true);
  461. Other ->
  462. ?debugFmt("unexpected trailing data ~p", [Other]),
  463. ?assert(false)
  464. end;
  465. false ->
  466. ?assertEqual(Expected, Actual)
  467. end.
  468. error_logger_redirect_crash_test_() ->
  469. TestBody=fun(Name,CrashReason,Expected) -> {Name,
  470. fun() ->
  471. Pid = whereis(crash),
  472. crash(CrashReason),
  473. {Level, _, Msg,Metadata} = pop(),
  474. test_body(Expected, lists:flatten(Msg)),
  475. ?assertEqual(Pid,proplists:get_value(pid,Metadata)),
  476. ?assertEqual(lager_util:level_to_num(error),Level)
  477. end
  478. }
  479. end,
  480. {foreach,
  481. fun() ->
  482. error_logger:tty(false),
  483. application:load(lager),
  484. application:set_env(lager, error_logger_redirect, true),
  485. application:set_env(lager, handlers, [{?MODULE, error}]),
  486. application:start(lager),
  487. crash:start()
  488. end,
  489. fun(_) ->
  490. application:stop(lager),
  491. case whereis(crash) of
  492. undefined -> ok;
  493. Pid -> exit(Pid, kill)
  494. end,
  495. error_logger:tty(true)
  496. end,
  497. [
  498. {"again, there is nothing up my sleeve",
  499. fun() ->
  500. ?assertEqual(undefined, pop()),
  501. ?assertEqual(0, count())
  502. end
  503. },
  504. TestBody("bad return value",bad_return,"gen_server crash terminated with reason: bad return value: bleh"),
  505. TestBody("bad return value with string",bad_return_string,"gen_server crash terminated with reason: bad return value: {tuple,{tuple,\"string\"}}"),
  506. TestBody("bad return uncaught throw",throw,"gen_server crash terminated with reason: bad return value: a_ball"),
  507. TestBody("case clause",case_clause,"gen_server crash terminated with reason: no case clause matching {} in crash:handle_call/3"),
  508. TestBody("case clause string",case_clause_string,"gen_server crash terminated with reason: no case clause matching \"crash\" in crash:handle_call/3"),
  509. TestBody("function clause",function_clause,"gen_server crash terminated with reason: no function clause matching crash:function({})"),
  510. TestBody("if clause",if_clause,"gen_server crash terminated with reason: no true branch found while evaluating if expression in crash:handle_call/3"),
  511. TestBody("try clause",try_clause,"gen_server crash terminated with reason: no try clause matching [] in crash:handle_call/3"),
  512. TestBody("undefined function",undef,"gen_server crash terminated with reason: call to undefined function crash:booger/0 from crash:handle_call/3"),
  513. TestBody("bad math",badarith,"gen_server crash terminated with reason: bad arithmetic expression in crash:handle_call/3"),
  514. TestBody("bad match",badmatch,"gen_server crash terminated with reason: no match of right hand value {} in crash:handle_call/3"),
  515. 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"),
  516. TestBody("bad arg1",badarg1,"gen_server crash terminated with reason: bad argument in crash:handle_call/3"),
  517. 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"),
  518. TestBody("bad record",badrecord,"gen_server crash terminated with reason: bad record state in crash:handle_call/3"),
  519. TestBody("noproc",noproc,"gen_server crash terminated with reason: no such process or port in call to gen_event:call(foo, bar, baz)"),
  520. TestBody("badfun",badfun,"gen_server crash terminated with reason: bad function booger in crash:handle_call/3")
  521. ]
  522. }.
  523. error_logger_redirect_test_() ->
  524. {foreach,
  525. fun() ->
  526. error_logger:tty(false),
  527. application:load(lager),
  528. application:set_env(lager, error_logger_redirect, true),
  529. application:set_env(lager, handlers, [{?MODULE, info}]),
  530. application:start(lager),
  531. lager:log(error, self(), "flush flush"),
  532. timer:sleep(100),
  533. gen_event:call(lager_event, ?MODULE, flush)
  534. end,
  535. fun(_) ->
  536. application:stop(lager),
  537. error_logger:tty(true)
  538. end,
  539. [
  540. {"error reports are printed",
  541. fun() ->
  542. sync_error_logger:error_report([{this, is}, a, {silly, format}]),
  543. _ = gen_event:which_handlers(error_logger),
  544. {Level, _, Msg,Metadata} = pop(),
  545. ?assertEqual(lager_util:level_to_num(error),Level),
  546. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  547. Expected = "this: is, a, silly: format",
  548. ?assertEqual(Expected, lists:flatten(Msg))
  549. end
  550. },
  551. {"string error reports are printed",
  552. fun() ->
  553. sync_error_logger:error_report("this is less silly"),
  554. _ = gen_event:which_handlers(error_logger),
  555. {Level, _, Msg,Metadata} = pop(),
  556. ?assertEqual(lager_util:level_to_num(error),Level),
  557. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  558. Expected = "this is less silly",
  559. ?assertEqual(Expected, lists:flatten(Msg))
  560. end
  561. },
  562. {"error messages are printed",
  563. fun() ->
  564. sync_error_logger:error_msg("doom, doom has come upon you all"),
  565. _ = gen_event:which_handlers(error_logger),
  566. {Level, _, Msg,Metadata} = pop(),
  567. ?assertEqual(lager_util:level_to_num(error),Level),
  568. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  569. Expected = "doom, doom has come upon you all",
  570. ?assertEqual(Expected, lists:flatten(Msg))
  571. end
  572. },
  573. {"error messages are truncated at 4096 characters",
  574. fun() ->
  575. sync_error_logger:error_msg("doom, doom has come upon you all ~p", [string:copies("doom", 10000)]),
  576. _ = gen_event:which_handlers(error_logger),
  577. {_, _, Msg,_Metadata} = pop(),
  578. ?assert(length(lists:flatten(Msg)) < 5100)
  579. end
  580. },
  581. {"info reports are printed",
  582. fun() ->
  583. sync_error_logger:info_report([{this, is}, a, {silly, format}]),
  584. _ = gen_event:which_handlers(error_logger),
  585. {Level, _, Msg,Metadata} = pop(),
  586. ?assertEqual(lager_util:level_to_num(info),Level),
  587. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  588. Expected = "this: is, a, silly: format",
  589. ?assertEqual(Expected, lists:flatten(Msg))
  590. end
  591. },
  592. {"info reports are truncated at 4096 characters",
  593. fun() ->
  594. sync_error_logger:info_report([[{this, is}, a, {silly, format}] || _ <- lists:seq(0, 600)]),
  595. _ = gen_event:which_handlers(error_logger),
  596. {Level, _, Msg,Metadata} = pop(),
  597. ?assertEqual(lager_util:level_to_num(info),Level),
  598. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  599. ?assert(length(lists:flatten(Msg)) < 5000)
  600. end
  601. },
  602. {"single term info reports are printed",
  603. fun() ->
  604. sync_error_logger:info_report({foolish, bees}),
  605. _ = gen_event:which_handlers(error_logger),
  606. {Level, _, Msg,Metadata} = pop(),
  607. ?assertEqual(lager_util:level_to_num(info),Level),
  608. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  609. ?assertEqual("{foolish,bees}", lists:flatten(Msg))
  610. end
  611. },
  612. {"single term error reports are printed",
  613. fun() ->
  614. sync_error_logger:error_report({foolish, bees}),
  615. _ = gen_event:which_handlers(error_logger),
  616. {Level, _, Msg,Metadata} = pop(),
  617. ?assertEqual(lager_util:level_to_num(error),Level),
  618. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  619. ?assertEqual("{foolish,bees}", lists:flatten(Msg))
  620. end
  621. },
  622. {"string info reports are printed",
  623. fun() ->
  624. sync_error_logger:info_report("this is less silly"),
  625. _ = gen_event:which_handlers(error_logger),
  626. {Level, _, Msg,Metadata} = pop(),
  627. ?assertEqual(lager_util:level_to_num(info),Level),
  628. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  629. ?assertEqual("this is less silly", lists:flatten(Msg))
  630. end
  631. },
  632. {"string info reports are truncated at 4096 characters",
  633. fun() ->
  634. sync_error_logger:info_report(string:copies("this is less silly", 1000)),
  635. _ = gen_event:which_handlers(error_logger),
  636. {Level, _, Msg,Metadata} = pop(),
  637. ?assertEqual(lager_util:level_to_num(info),Level),
  638. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  639. ?assert(length(lists:flatten(Msg)) < 5100)
  640. end
  641. },
  642. {"strings in a mixed report are printed as strings",
  643. fun() ->
  644. sync_error_logger:info_report(["this is less silly", {than, "this"}]),
  645. _ = gen_event:which_handlers(error_logger),
  646. {Level, _, Msg,Metadata} = pop(),
  647. ?assertEqual(lager_util:level_to_num(info),Level),
  648. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  649. ?assertEqual("\"this is less silly\", than: \"this\"", lists:flatten(Msg))
  650. end
  651. },
  652. {"info messages are printed",
  653. fun() ->
  654. sync_error_logger:info_msg("doom, doom has come upon you all"),
  655. _ = gen_event:which_handlers(error_logger),
  656. {Level, _, Msg,Metadata} = pop(),
  657. ?assertEqual(lager_util:level_to_num(info),Level),
  658. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  659. ?assertEqual("doom, doom has come upon you all", lists:flatten(Msg))
  660. end
  661. },
  662. {"info messages are truncated at 4096 characters",
  663. fun() ->
  664. sync_error_logger:info_msg("doom, doom has come upon you all ~p", [string:copies("doom", 10000)]),
  665. _ = gen_event:which_handlers(error_logger),
  666. {Level, _, Msg,Metadata} = pop(),
  667. ?assertEqual(lager_util:level_to_num(info),Level),
  668. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  669. ?assert(length(lists:flatten(Msg)) < 5100)
  670. end
  671. },
  672. {"warning messages are printed at the correct level",
  673. fun() ->
  674. sync_error_logger:warning_msg("doom, doom has come upon you all"),
  675. Map = error_logger:warning_map(),
  676. _ = gen_event:which_handlers(error_logger),
  677. {Level, _, Msg,Metadata} = pop(),
  678. ?assertEqual(lager_util:level_to_num(Map),Level),
  679. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  680. ?assertEqual("doom, doom has come upon you all", lists:flatten(Msg))
  681. end
  682. },
  683. {"warning reports are printed at the correct level",
  684. fun() ->
  685. sync_error_logger:warning_report([{i, like}, pie]),
  686. Map = error_logger:warning_map(),
  687. _ = gen_event:which_handlers(error_logger),
  688. {Level, _, Msg,Metadata} = pop(),
  689. ?assertEqual(lager_util:level_to_num(Map),Level),
  690. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  691. ?assertEqual("i: like, pie", lists:flatten(Msg))
  692. end
  693. },
  694. {"single term warning reports are printed at the correct level",
  695. fun() ->
  696. sync_error_logger:warning_report({foolish, bees}),
  697. Map = error_logger:warning_map(),
  698. _ = gen_event:which_handlers(error_logger),
  699. {Level, _, Msg,Metadata} = pop(),
  700. ?assertEqual(lager_util:level_to_num(Map),Level),
  701. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  702. ?assertEqual("{foolish,bees}", lists:flatten(Msg))
  703. end
  704. },
  705. {"application stop reports",
  706. fun() ->
  707. sync_error_logger:info_report([{application, foo}, {exited, quittin_time}, {type, lazy}]),
  708. _ = gen_event:which_handlers(error_logger),
  709. {Level, _, Msg,Metadata} = pop(),
  710. ?assertEqual(lager_util:level_to_num(info),Level),
  711. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  712. ?assertEqual("Application foo exited with reason: quittin_time", lists:flatten(Msg))
  713. end
  714. },
  715. {"supervisor reports",
  716. fun() ->
  717. sync_error_logger:error_report(supervisor_report, [{errorContext, france}, {offender, [{name, mini_steve}, {mfargs, {a, b, [c]}}, {pid, bleh}]}, {reason, fired}, {supervisor, {local, steve}}]),
  718. _ = gen_event:which_handlers(error_logger),
  719. {Level, _, Msg,Metadata} = pop(),
  720. ?assertEqual(lager_util:level_to_num(error),Level),
  721. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  722. ?assertEqual("Supervisor steve had child mini_steve started with a:b(c) at bleh exit with reason fired in context france", lists:flatten(Msg))
  723. end
  724. },
  725. {"supervisor reports with real error",
  726. fun() ->
  727. 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}}]),
  728. _ = gen_event:which_handlers(error_logger),
  729. {Level, _, Msg,Metadata} = pop(),
  730. ?assertEqual(lager_util:level_to_num(error),Level),
  731. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  732. ?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))
  733. end
  734. },
  735. {"supervisor reports with real error and pid",
  736. fun() ->
  737. 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}]),
  738. _ = gen_event:which_handlers(error_logger),
  739. {Level, _, Msg,Metadata} = pop(),
  740. ?assertEqual(lager_util:level_to_num(error),Level),
  741. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  742. ?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))
  743. end
  744. },
  745. {"supervisor_bridge reports",
  746. fun() ->
  747. sync_error_logger:error_report(supervisor_report, [{errorContext, france}, {offender, [{mod, mini_steve}, {pid, bleh}]}, {reason, fired}, {supervisor, {local, steve}}]),
  748. _ = gen_event:which_handlers(error_logger),
  749. {Level, _, Msg,Metadata} = pop(),
  750. ?assertEqual(lager_util:level_to_num(error),Level),
  751. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  752. ?assertEqual("Supervisor steve had child at module mini_steve at bleh exit with reason fired in context france", lists:flatten(Msg))
  753. end
  754. },
  755. {"application progress report",
  756. fun() ->
  757. sync_error_logger:info_report(progress, [{application, foo}, {started_at, node()}]),
  758. _ = gen_event:which_handlers(error_logger),
  759. {Level, _, Msg,Metadata} = pop(),
  760. ?assertEqual(lager_util:level_to_num(info),Level),
  761. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  762. Expected = lists:flatten(io_lib:format("Application foo started on node ~w", [node()])),
  763. ?assertEqual(Expected, lists:flatten(Msg))
  764. end
  765. },
  766. {"supervisor progress report",
  767. fun() ->
  768. lager:set_loglevel(?MODULE, debug),
  769. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  770. sync_error_logger:info_report(progress, [{supervisor, {local, foo}}, {started, [{mfargs, {foo, bar, 1}}, {pid, baz}]}]),
  771. _ = gen_event:which_handlers(error_logger),
  772. {Level, _, Msg,Metadata} = pop(),
  773. ?assertEqual(lager_util:level_to_num(debug),Level),
  774. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  775. ?assertEqual("Supervisor foo started foo:bar/1 at pid baz", lists:flatten(Msg))
  776. end
  777. },
  778. {"supervisor progress report with pid",
  779. fun() ->
  780. lager:set_loglevel(?MODULE, debug),
  781. ?assertEqual({?DEBUG bor ?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  782. sync_error_logger:info_report(progress, [{supervisor, somepid}, {started, [{mfargs, {foo, bar, 1}}, {pid, baz}]}]),
  783. _ = gen_event:which_handlers(error_logger),
  784. {Level, _, Msg,Metadata} = pop(),
  785. ?assertEqual(lager_util:level_to_num(debug),Level),
  786. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  787. ?assertEqual("Supervisor somepid started foo:bar/1 at pid baz", lists:flatten(Msg))
  788. end
  789. },
  790. {"crash report for emfile",
  791. fun() ->
  792. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, emfile, [{stack, trace, 1}]}}], []]),
  793. _ = gen_event:which_handlers(error_logger),
  794. {Level, _, Msg,Metadata} = pop(),
  795. ?assertEqual(lager_util:level_to_num(error),Level),
  796. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  797. 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()])),
  798. ?assertEqual(Expected, lists:flatten(Msg))
  799. end
  800. },
  801. {"crash report for system process limit",
  802. fun() ->
  803. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, spawn, 1}]}}], []]),
  804. _ = gen_event:which_handlers(error_logger),
  805. {Level, _, Msg,Metadata} = pop(),
  806. ?assertEqual(lager_util:level_to_num(error),Level),
  807. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  808. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: maximum number of processes exceeded", [self()])),
  809. ?assertEqual(Expected, lists:flatten(Msg))
  810. end
  811. },
  812. {"crash report for system process limit2",
  813. fun() ->
  814. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, spawn_opt, 1}]}}], []]),
  815. _ = gen_event:which_handlers(error_logger),
  816. {Level, _, Msg,Metadata} = pop(),
  817. ?assertEqual(lager_util:level_to_num(error),Level),
  818. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  819. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: maximum number of processes exceeded", [self()])),
  820. ?assertEqual(Expected, lists:flatten(Msg))
  821. end
  822. },
  823. {"crash report for system port limit",
  824. fun() ->
  825. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, open_port, 1}]}}], []]),
  826. _ = gen_event:which_handlers(error_logger),
  827. {Level, _, Msg,Metadata} = pop(),
  828. ?assertEqual(lager_util:level_to_num(error),Level),
  829. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  830. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~w with 0 neighbours crashed with reason: system limit: maximum number of ports exceeded", [self()])),
  831. ?assertEqual(Expected, lists:flatten(Msg))
  832. end
  833. },
  834. {"crash report for system port limit",
  835. fun() ->
  836. sync_error_logger:error_report(crash_report, [[{pid, self()}, {registered_name, []}, {error_info, {error, system_limit, [{erlang, list_to_atom, 1}]}}], []]),
  837. _ = gen_event:which_handlers(error_logger),
  838. {Level, _, Msg,Metadata} = pop(),
  839. ?assertEqual(lager_util:level_to_num(error),Level),
  840. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  841. 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()])),
  842. ?assertEqual(Expected, lists:flatten(Msg))
  843. end
  844. },
  845. {"crash report for system ets table limit",
  846. fun() ->
  847. 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}]}}], []]),
  848. _ = gen_event:which_handlers(error_logger),
  849. {Level, _, Msg,Metadata} = pop(),
  850. ?assertEqual(lager_util:level_to_num(error),Level),
  851. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  852. 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])),
  853. ?assertEqual(Expected, lists:flatten(Msg))
  854. end
  855. },
  856. {"crash report for unknown system limit should be truncated at 500 characters",
  857. fun() ->
  858. sync_error_logger:error_report(crash_report, [[{pid, self()}, {error_info, {error, system_limit, [{wtf,boom,[string:copies("aaaa", 4096)]}]}}], []]),
  859. _ = gen_event:which_handlers(error_logger),
  860. {_, _, Msg,_Metadata} = pop(),
  861. ?assert(length(lists:flatten(Msg)) > 550),
  862. ?assert(length(lists:flatten(Msg)) < 600)
  863. end
  864. },
  865. {"crash reports for 'special processes' should be handled right - function_clause",
  866. fun() ->
  867. {ok, Pid} = special_process:start(),
  868. unlink(Pid),
  869. Pid ! function_clause,
  870. timer:sleep(500),
  871. _ = gen_event:which_handlers(error_logger),
  872. {_, _, Msg, _Metadata} = pop(),
  873. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~p with 0 neighbours crashed with reason: no function clause matching special_process:foo(bar)",
  874. [Pid])),
  875. test_body(Expected, lists:flatten(Msg))
  876. end
  877. },
  878. {"crash reports for 'special processes' should be handled right - case_clause",
  879. fun() ->
  880. {ok, Pid} = special_process:start(),
  881. unlink(Pid),
  882. Pid ! {case_clause, wtf},
  883. timer:sleep(500),
  884. _ = gen_event:which_handlers(error_logger),
  885. {_, _, Msg, _Metadata} = pop(),
  886. 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",
  887. [Pid])),
  888. test_body(Expected, lists:flatten(Msg))
  889. end
  890. },
  891. {"crash reports for 'special processes' should be handled right - exit",
  892. fun() ->
  893. {ok, Pid} = special_process:start(),
  894. unlink(Pid),
  895. Pid ! exit,
  896. timer:sleep(500),
  897. _ = gen_event:which_handlers(error_logger),
  898. {_, _, Msg, _Metadata} = pop(),
  899. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~p with 0 neighbours exited with reason: byebye in special_process:loop/0",
  900. [Pid])),
  901. test_body(Expected, lists:flatten(Msg))
  902. end
  903. },
  904. {"crash reports for 'special processes' should be handled right - error",
  905. fun() ->
  906. {ok, Pid} = special_process:start(),
  907. unlink(Pid),
  908. Pid ! error,
  909. timer:sleep(500),
  910. _ = gen_event:which_handlers(error_logger),
  911. {_, _, Msg, _Metadata} = pop(),
  912. Expected = lists:flatten(io_lib:format("CRASH REPORT Process ~p with 0 neighbours crashed with reason: mybad in special_process:loop/0",
  913. [Pid])),
  914. test_body(Expected, lists:flatten(Msg))
  915. end
  916. },
  917. {"webmachine error reports",
  918. fun() ->
  919. Path = "/cgi-bin/phpmyadmin",
  920. Reason = {error,{error,{badmatch,{error,timeout}},
  921. [{myapp,dostuff,2,[{file,"src/myapp.erl"},{line,123}]},
  922. {webmachine_resource,resource_call,3,[{file,"src/webmachine_resource.erl"},{line,169}]}]}},
  923. sync_error_logger:error_msg("webmachine error: path=~p~n~p~n", [Path, Reason]),
  924. _ = gen_event:which_handlers(error_logger),
  925. {Level, _, Msg,Metadata} = pop(),
  926. ?assertEqual(lager_util:level_to_num(error),Level),
  927. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  928. ?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))
  929. end
  930. },
  931. {"Cowboy error reports, 8 arg version",
  932. fun() ->
  933. Stack = [{my_handler,init, 3,[{file,"src/my_handler.erl"},{line,123}]},
  934. {cowboy_handler,handler_init,4,[{file,"src/cowboy_handler.erl"},{line,169}]}],
  935. sync_error_logger:error_msg(
  936. "** Cowboy handler ~p terminating in ~p/~p~n"
  937. " for the reason ~p:~p~n"
  938. "** Options were ~p~n"
  939. "** Request was ~p~n"
  940. "** Stacktrace: ~p~n~n",
  941. [my_handler, init, 3, error, {badmatch, {error, timeout}}, [],
  942. "Request", Stack]),
  943. _ = gen_event:which_handlers(error_logger),
  944. {Level, _, Msg,Metadata} = pop(),
  945. ?assertEqual(lager_util:level_to_num(error),Level),
  946. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  947. ?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))
  948. end
  949. },
  950. {"Cowboy error reports, 10 arg version",
  951. fun() ->
  952. Stack = [{my_handler,somecallback, 3,[{file,"src/my_handler.erl"},{line,123}]},
  953. {cowboy_handler,handler_init,4,[{file,"src/cowboy_handler.erl"},{line,169}]}],
  954. sync_error_logger:error_msg(
  955. "** Cowboy handler ~p terminating in ~p/~p~n"
  956. " for the reason ~p:~p~n** Message was ~p~n"
  957. "** Options were ~p~n** Handler state was ~p~n"
  958. "** Request was ~p~n** Stacktrace: ~p~n~n",
  959. [my_handler, somecallback, 3, error, {badmatch, {error, timeout}}, hello, [],
  960. {}, "Request", Stack]),
  961. _ = gen_event:which_handlers(error_logger),
  962. {Level, _, Msg,Metadata} = pop(),
  963. ?assertEqual(lager_util:level_to_num(error),Level),
  964. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  965. ?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))
  966. end
  967. },
  968. {"Cowboy error reports, 5 arg version",
  969. fun() ->
  970. sync_error_logger:error_msg(
  971. "** Cowboy handler ~p terminating; "
  972. "function ~p/~p was not exported~n"
  973. "** Request was ~p~n** State was ~p~n~n",
  974. [my_handler, to_json, 2, "Request", {}]),
  975. _ = gen_event:which_handlers(error_logger),
  976. {Level, _, Msg,Metadata} = pop(),
  977. ?assertEqual(lager_util:level_to_num(error),Level),
  978. ?assertEqual(self(),proplists:get_value(pid,Metadata)),
  979. ?assertEqual("Cowboy handler my_handler terminated with reason: call to undefined function my_handler:to_json/2", lists:flatten(Msg))
  980. end
  981. },
  982. {"messages should not be generated if they don't satisfy the threshold",
  983. fun() ->
  984. lager:set_loglevel(?MODULE, error),
  985. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  986. sync_error_logger:info_report([hello, world]),
  987. _ = gen_event:which_handlers(error_logger),
  988. ?assertEqual(0, count()),
  989. ?assertEqual(0, count_ignored()),
  990. lager:set_loglevel(?MODULE, info),
  991. ?assertEqual({?INFO bor ?NOTICE bor ?WARNING bor ?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  992. sync_error_logger:info_report([hello, world]),
  993. _ = gen_event:which_handlers(error_logger),
  994. ?assertEqual(1, count()),
  995. ?assertEqual(0, count_ignored()),
  996. lager:set_loglevel(?MODULE, error),
  997. ?assertEqual({?ERROR bor ?CRITICAL bor ?ALERT bor ?EMERGENCY, []}, lager_config:get(loglevel)),
  998. lager_config:set(loglevel, {element(2, lager_util:config_to_mask(debug)), []}),
  999. sync_error_logger:info_report([hello, world]),
  1000. _ = gen_event:which_handlers(error_logger),
  1001. ?assertEqual(1, count()),
  1002. ?assertEqual(1, count_ignored())
  1003. end
  1004. }
  1005. ]
  1006. }.
  1007. safe_format_test() ->
  1008. ?assertEqual("foo bar", lists:flatten(lager:safe_format("~p ~p", [foo, bar], 1024))),
  1009. ?assertEqual("FORMAT ERROR: \"~p ~p ~p\" [foo,bar]", lists:flatten(lager:safe_format("~p ~p ~p", [foo, bar], 1024))),
  1010. ok.
  1011. async_threshold_test_() ->
  1012. {foreach,
  1013. fun() ->
  1014. error_logger:tty(false),
  1015. application:load(lager),
  1016. application:set_env(lager, error_logger_redirect, false),
  1017. application:set_env(lager, async_threshold, 10),
  1018. application:set_env(lager, handlers, [{?MODULE, info}]),
  1019. application:start(lager)
  1020. end,
  1021. fun(_) ->
  1022. application:unset_env(lager, async_threshold),
  1023. application:stop(lager),
  1024. error_logger:tty(true)
  1025. end,
  1026. [
  1027. {"async threshold works",
  1028. fun() ->
  1029. %% we start out async
  1030. ?assertEqual(true, lager_config:get(async)),
  1031. %% put a ton of things in the queue
  1032. Workers = [spawn_monitor(fun() -> [lager:info("hello world") || _ <- lists:seq(1, 1000)] end) || _ <- lists:seq(1, 10)],
  1033. %% serialize on mailbox
  1034. _ = gen_event:which_handlers(lager_event),
  1035. %% there should be a ton of outstanding messages now, so async is false
  1036. ?assertEqual(false, lager_config:get(async)),
  1037. %% wait for all the workers to return, meaning that all the messages have been logged (since we're in sync mode)
  1038. collect_workers(Workers),
  1039. %% serialize ont the mailbox again
  1040. _ = gen_event:which_handlers(lager_event),
  1041. %% just in case...
  1042. timer:sleep(100),
  1043. %% async is true again now that the mailbox has drained
  1044. ?assertEqual(true, lager_config:get(async)),
  1045. ok
  1046. end
  1047. }
  1048. ]
  1049. }.
  1050. collect_workers([]) ->
  1051. ok;
  1052. collect_workers(Workers) ->
  1053. receive
  1054. {'DOWN', Ref, _, _, _} ->
  1055. collect_workers(lists:keydelete(Ref, 2, Workers))
  1056. end.
  1057. -endif.