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

1852 строки
94 KiB

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