-
Notifications
You must be signed in to change notification settings - Fork 3k
/
ct_logs.erl
3461 lines (3181 loc) · 112 KB
/
ct_logs.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2003-2023. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%% Logging functionality for Common Test Framework.
%%%
%%% This module implements:
%%%
%%% Internal logging of activities in Common Test Framework, and
%%% Compilation of test results into index pages on several levels
-module(ct_logs).
-export([init/3, close/3, init_tc/1, end_tc/1]).
-export([register_groupleader/2, unregister_groupleader/1]).
-export([get_log_dir/0, get_log_dir/1]).
-export([log/3, start_log/1, cont_log/2, cont_log_no_timestamp/2, end_log/0]).
-export([set_stylesheet/2, clear_stylesheet/1]).
-export([add_external_logs/1, add_link/3]).
-export([make_last_run_index/0]).
-export([make_all_suites_index/2,make_all_runs_index/2]).
-export([get_ts_html_wrapper/5, escape_chars/1]).
-export([xhtml/2, locate_priv_file/1, make_relative/1]).
-export([insert_javascript/1]).
-export([uri/1]).
-export([parse_keep_logs/1]).
%% Logging stuff directly from testcase
-export([tc_log/3, tc_log/4, tc_log/5, tc_log/6,
tc_log_async/3, tc_log_async/5,
tc_print/3, tc_print/4, tc_print/5,
tc_pal/3, tc_pal/4, tc_pal/5, ct_log/3,
basic_html/0]).
%% Simulate logger process for use without ct environment running
-export([simulate/0]).
-include("ct.hrl").
-include("ct_event.hrl").
-include("ct_util.hrl").
-include_lib("kernel/include/file.hrl").
-define(suitelog_name,"suite.log").
-define(run_summary, "suite.summary").
-define(logdir_ext, ".logs").
-define(ct_log_name, "ctlog.html").
-define(all_runs_name, "all_runs.html").
-define(index_name, "index.html").
-define(totals_name, "totals.info").
-define(log_cache_name, "ct_log_cache").
-define(misc_io_log, "misc_io.log.html").
-define(coverlog_name, "cover.html"). % must be same as in test_server_ctrl
-define(table_color1,"#ADD8E6").
-define(table_color2,"#E4F0FE").
-define(table_color3,"#F0F8FF").
-define(testname_width, 60).
-define(abs(Name), filename:absname(Name)).
-define(now, os:timestamp()).
-record(log_cache, {version,
all_runs = [],
tests = []}).
%%%-----------------------------------------------------------------
%%% -spec init(Mode, Verbosity, CustomStylesheet) -> Result
%%% Mode = normal | interactive
%%% CustomStylesheet = string() | undefined | unknown
%%% Result = {StartTime,LogDir}
%%% StartTime = term()
%%% LogDir = string()
%%%
%%% Initiate the logging mechanism (tool-internal use only).
%%%
%%% This function is called by ct_util.erl when testing is
%%% started. A new directory named ct_run.<timestamp> is created
%%% and all logs are stored under this directory.
%%%
init(Mode, Verbosity, CustomStylesheet) ->
Self = self(),
Pid = spawn_link(fun() -> logger(Self, Mode, Verbosity, CustomStylesheet) end),
MRef = erlang:monitor(process,Pid),
receive
{started,Pid,Result} ->
erlang:demonitor(MRef, [flush]),
Result;
{'DOWN',MRef,process,_,Reason} ->
exit({could_not_start_process,?MODULE,Reason})
end.
date2str({{YY,MM,DD},{H,M,S}}) ->
lists:flatten(io_lib:format("~w-~2.2.0w-~2.2.0w_~2.2.0w.~2.2.0w.~2.2.0w",
[YY,MM,DD,H,M,S])).
logdir_prefix() ->
"ct_run".
logdir_node_prefix() ->
logdir_prefix() ++ "." ++ atom_to_list(node()).
make_dirname(DateTime) ->
logdir_node_prefix() ++ "." ++ date2str(DateTime).
datestr_from_dirname([Y1,Y2,Y3,Y4,$-,Mo1,Mo2,$-,D1,D2,$_,
H1,H2,$.,M1,M2,$.,S1,S2 | _]) ->
[Y1,Y2,Y3,Y4,$-,Mo1,Mo2,$-,D1,D2,$_,
H1,H2,$.,M1,M2,$.,S1,S2];
datestr_from_dirname([_Ch | Rest]) ->
datestr_from_dirname(Rest);
datestr_from_dirname([]) ->
"".
%%%-----------------------------------------------------------------
%%% -spec close(Info, StartDir, CustomStylesheet) -> ok
%%%
%%% Create index pages with test results and close the CT Log
%%% (tool-internal use only).
close(Info, StartDir, CustomStylesheet) ->
%% close executes on the ct_util process, not on the logger process
%% so we need to use a local copy of the log cache data
LogCacheBin =
case make_last_run_index() of
{error, Reason} -> % log server not responding
io:format("Warning! ct_logs not responding: ~tp~n", [Reason]),
undefined;
LCB ->
LCB
end,
put(ct_log_cache,LogCacheBin),
Cache2File = fun() ->
case get(ct_log_cache) of
undefined ->
ok;
CacheBin ->
%% save final version of the log cache to file
write_log_cache(CacheBin),
put(ct_log_cache,undefined)
end
end,
ct_event:notify(#event{name=stop_logging,node=node(),data=[]}),
case whereis(?MODULE) of
Pid when is_pid(Pid) ->
MRef = erlang:monitor(process,Pid),
?MODULE ! stop,
receive
{'DOWN',MRef,process,_,_} ->
ok
end;
undefined ->
ok
end,
if Info == clean ->
case cleanup() of
ok ->
ok;
Error ->
io:format("Warning! Cleanup failed: ~tp~n", [Error])
end,
_ = make_all_suites_index(stop, CustomStylesheet),
make_all_runs_index(stop, CustomStylesheet),
Cache2File();
true ->
ok = file:set_cwd(".."),
_ = make_all_suites_index(stop, CustomStylesheet),
make_all_runs_index(stop, CustomStylesheet),
Cache2File(),
case ct_util:get_profile_data(browser, StartDir) of
undefined ->
ok;
BrowserData ->
case {proplists:get_value(prog, BrowserData),
proplists:get_value(args, BrowserData),
proplists:get_value(page, BrowserData)} of
{Prog,Args,Page} when is_list(Args),
is_list(Page) ->
URL = "\"file://" ++ ?abs(Page) ++ "\"",
ct_util:open_url(Prog, Args, URL);
_ ->
ok
end
end
end,
ok.
%%%-----------------------------------------------------------------
%%% -spec get_stylesheet() -> string() | undefined
get_stylesheet() ->
call(get_stylesheet).
%%%-----------------------------------------------------------------
%%% -spec set_stylesheet(TC,SSFile) -> ok
set_stylesheet(TC, SSFile) ->
cast({set_stylesheet,TC,SSFile}).
%%%-----------------------------------------------------------------
%%% -spec clear_stylesheet(TC) -> ok
clear_stylesheet(TC) ->
cast({clear_stylesheet,TC}).
%%%-----------------------------------------------------------------
%%% -spec get_log_dir() -> {ok,Dir} | {error,Reason}
get_log_dir() ->
get_log_dir(false).
%%%-----------------------------------------------------------------
%%% -spec get_log_dir(ReturnAbsName) -> {ok,Dir} | {error,Reason}
get_log_dir(ReturnAbsName) ->
case call({get_log_dir,ReturnAbsName}) of
{error,does_not_exist} when ReturnAbsName == true ->
{ok,filename:absname(".")};
{error,does_not_exist} ->
{ok,"."};
Result ->
Result
end.
%%%-----------------------------------------------------------------
%%% make_last_run_index() -> ok
make_last_run_index() ->
call(make_last_run_index).
call(Msg) ->
case whereis(?MODULE) of
undefined ->
{error,does_not_exist};
Pid ->
MRef = erlang:monitor(process,Pid),
Ref = make_ref(),
Pid ! {Msg,{self(),Ref}},
receive
{Ref, Result} ->
erlang:demonitor(MRef, [flush]),
Result;
{'DOWN',MRef,process,_,Reason} ->
{error,{process_down,?MODULE,Reason}}
end
end.
return({To,Ref},Result) ->
To ! {Ref, Result},
ok.
cast(Msg) ->
case whereis(?MODULE) of
undefined ->
io:format("Warning: ct_logs not started~n"),
{_,_,_,_,_,_,Content,_} = Msg,
FormatArgs = get_format_args(Content),
_ = [io:format(Format, Args) || {Format, Args} <- FormatArgs],
ok;
_Pid ->
?MODULE ! Msg,
ok
end.
get_format_args(Content) ->
lists:map(fun(C) ->
case C of
{_, FA, _} -> FA;
{_, _} -> C
end
end, Content).
%%%-----------------------------------------------------------------
%%% -spec init_tc(RefreshLog) -> ok
%%%
%%% Test case initiation (tool-internal use only).
%%%
%%% This function is called by ct_framework:init_tc/3
init_tc(RefreshLog) ->
call({init_tc,self(),group_leader(),RefreshLog}),
tc_io_format(group_leader(), xhtml("", "<br />"), []),
ok.
%%%-----------------------------------------------------------------
%%% -spec end_tc(TCPid) -> ok
%%%
%%% Test case clean up (tool-internal use only).
%%%
%%% This function is called by ct_framework:end_tc/3
end_tc(TCPid) ->
%% use call here so that the TC process will wait and receive
%% possible exit signals from ct_logs before end_tc returns ok
call({end_tc,TCPid}).
%%%-----------------------------------------------------------------
%%% -spec register_groupleader(Pid,GroupLeader) -> ok
%%%
%%% To enable logging to a group leader (tool-internal use only).
%%%
%%% This function is called by ct_framework:report/2
register_groupleader(Pid,GroupLeader) ->
call({register_groupleader,Pid,GroupLeader}),
ok.
%%%-----------------------------------------------------------------
%%% -spec unregister_groupleader(Pid) -> ok
%%%
%%% To disable logging to a group leader (tool-internal use only).
%%%
%%% This function is called by ct_framework:report/2
unregister_groupleader(Pid) ->
call({unregister_groupleader,Pid}),
ok.
%%%-----------------------------------------------------------------
%%% -spec log(Heading,Format,Args) -> ok
%%%
%%% Log internal activity (tool-internal use only).
%%%
%%% This function writes an entry to the currently active log,
%%% i.e. either the CT log or a test case log.
%%%
%%% Heading is a short string indicating what type of
%%% activity it is. Format and Args is the
%%% data to log (as in io:format(Format,Args)).
log(Heading,Format,Args) ->
cast({log,sync,self(),group_leader(),ct_internal,?MAX_IMPORTANCE,
[{hd,int_header(),[log_timestamp(?now),Heading]},
{Format,Args},
{ft,int_footer(),[]}],
true}),
ok.
%%%-----------------------------------------------------------------
%%% -spec start_log(Heading) -> ok
%%%
%%% Starts the logging of an activity (tool-internal use only).
%%%
%%% This function must be used in combination with
%%% cont_log/2 and end_log/0. The intention
%%% is to call start_log once, then cont_log
%%% any number of times and finally end_log once.
%%%
%%% For information about the parameters, see log/3.
%%%
%%% See log/3, cont_log/2, and end_log/0.
start_log(Heading) ->
cast({log,sync,self(),group_leader(),ct_internal,?MAX_IMPORTANCE,
[{hd,int_header(),[log_timestamp(?now),Heading]}],false}),
ok.
%%%-----------------------------------------------------------------
%%% -spec cont_log(Format,Args) -> ok
%%%
%%% Adds information about an activity (tool-internal use only).
%%%
%%% See start_log/1 and end_log/0.
cont_log([],[]) ->
ok;
cont_log(Format,Args) ->
maybe_log_timestamp(),
cast({log,sync,self(),group_leader(),ct_internal,?MAX_IMPORTANCE,
[{Format,Args}],true}),
ok.
%%%-----------------------------------------------------------------
%%% -spec cont_log_no_timestamp(Format,Args) -> ok
%%%
%%% Adds information about an activity (tool-internal use only).
%%%
%%% See start_log/1 and end_log/0.
cont_log_no_timestamp([],[]) ->
ok;
cont_log_no_timestamp(Format,Args) ->
cast({log,sync,self(),group_leader(),ct_internal,?MAX_IMPORTANCE,
[{Format,Args}],true}),
ok.
%%%-----------------------------------------------------------------
%%% -spec end_log() -> ok
%%%
%%% Ends the logging of an activity (tool-internal use only).
%%%
%%% See start_log/1 and cont_log/2.
end_log() ->
cast({log,sync,self(),group_leader(),ct_internal,?MAX_IMPORTANCE,
[{ft,int_footer(), []}],false}),
ok.
%%%-----------------------------------------------------------------
%%% -spec add_external_logs(Logs) -> ok
%%% Logs = [Log]
%%% Log = string()
%%%
%%% Print a link to each given Log in the test case
%%% log.
%%%
%%% The given Logs must exist in the priv dir of the
%%% calling test suite.
add_external_logs(Logs) ->
start_log("External Logs"),
[cont_log("<a href=\"~ts\">~ts</a>\n",
[uri(filename:join("log_private",Log)),Log]) || Log <- Logs],
end_log().
%%%-----------------------------------------------------------------
%%% -spec add_link(Heading,File,Type) -> ok
%%% Heading = string()
%%% File = string()
%%% Type = string()
%%%
%%% Print a link to a given file stored in the priv_dir of the
%%% calling test suite.
add_link(Heading,File,Type) ->
log(Heading,"<a href=\"~ts\" type=~tp>~ts</a>\n",
[uri(filename:join("log_private",File)),Type,File]).
%%%-----------------------------------------------------------------
%%% -spec tc_log(Category,Format,Args) -> ok
%%% Equivalent to tc_log(Category,?STD_IMPORTANCE,Format,Args)
tc_log(Category,Format,Args) ->
tc_log(Category,?STD_IMPORTANCE,"User",Format,Args,[]).
%%%-----------------------------------------------------------------
%%% -spec tc_log(Category,Importance,Format,Args) -> ok
%%% Equivalent to tc_log(Category,Importance,"User",Format,Args)
tc_log(Category,Importance,Format,Args) ->
tc_log(Category,Importance,"User",Format,Args,[]).
%%%-----------------------------------------------------------------
%%% -spec tc_log(Category,Importance,Format,Args) -> ok
%%% Equivalent to tc_log(Category,Importance,"User",Format,Args)
tc_log(Category,Importance,Format,Args,Opts) ->
tc_log(Category,Importance,"User",Format,Args,Opts).
%%%-----------------------------------------------------------------
%%% -spec tc_log(Category,Importance,Heading,Format,Args,Opts) -> ok
%%% Category = atom()
%%% Importance = integer()
%%% Heading = string()
%%% Format = string()
%%% Args = list()
%%% Opts = list()
%%%
%%% Printout from a testcase.
%%%
%%% This function is called by ct when logging
%%% stuff directly from a testcase (i.e. not from within the CT
%%% framework).
tc_log(Category,Importance,Heading,Format,Args,Opts) ->
Data =
case lists:member(no_css, Opts) of
true ->
[{Format,Args}];
false ->
Heading1 =
case proplists:get_value(heading, Opts) of
undefined -> Heading;
Str -> Str
end,
[{hd,div_header(Category,Heading1),[]},
{Format,Args},
{ft,div_footer(),[]}]
end,
cast({log,sync,self(),group_leader(),Category,Importance,Data,
lists:member(esc_chars, Opts)}),
ok.
%%%-----------------------------------------------------------------
%%% -spec tc_log_async(Category,Format,Args) -> ok
%%% Equivalent to tc_log_async(Category,?STD_IMPORTANCE,"User",Format,Args)
tc_log_async(Category,Format,Args) ->
tc_log_async(Category,?STD_IMPORTANCE,"User",Format,Args).
%%%-----------------------------------------------------------------
%%% -spec tc_log_async(Category,Importance,Format,Args) -> ok
%%% Category = atom()
%%% Importance = integer()
%%% Heading = string()
%%% Format = string()
%%% Args = list()
%%%
%%% Internal use only.
%%%
%%% This function is used to perform asynchronous printouts
%%% towards the test server IO handler. This is necessary in order
%%% to avoid deadlocks when e.g. the hook that handles SASL printouts
%%% prints to the test case log file at the same time test server
%%% asks ct_logs for an html wrapper.
tc_log_async(Category,Importance,Heading,Format,Args) ->
cast({log,async,self(),group_leader(),Category,Importance,
[{hd,div_header(Category,Heading),[]},
{Format,Args},
{ft,div_footer(),[]}],
true}),
ok.
%%%-----------------------------------------------------------------
%%% -spec tc_print(Category,Format,Args)
%%% Equivalent to tc_print(Category,?STD_IMPORTANCE,Format,Args,[])
tc_print(Category,Format,Args) ->
tc_print(Category,?STD_IMPORTANCE,Format,Args,[]).
%%%-----------------------------------------------------------------
%%% -spec tc_print(Category,Importance,Format,Args)
%%% Equivalent to tc_print(Category,Importance,Format,Args,[])
tc_print(Category,Importance,Format,Args) ->
tc_print(Category,Importance,Format,Args,[]).
%%%-----------------------------------------------------------------
%%% -spec tc_print(Category,Importance,Format,Args,Opts) -> ok
%%% Category = atom()
%%% Importance = integer()
%%% Format = string()
%%% Args = list()
%%% Opts = list()
%%%
%%% Console printout from a testcase.
%%%
%%% This function is called by ct when printing
%%% stuff from a testcase on the user console.
tc_print(Category,Importance,Format,Args,Opts) ->
VLvl = case ct_util:get_verbosity(Category) of
undefined ->
ct_util:get_verbosity('$unspecified');
{error,bad_invocation} ->
?MAX_VERBOSITY;
{error,_Failure} ->
?MAX_VERBOSITY;
Val ->
Val
end,
if Importance >= (100-VLvl) ->
Heading =
case proplists:get_value(heading, Opts) of
undefined -> atom_to_list(Category);
Hd -> Hd
end,
Str = lists:flatten([get_header(Heading),Format,"\n\n"]),
try
io:format(?def_gl, Str, Args)
catch
%% default group leader probably not started, or has stopped
_:_ -> io:format(user, Str, Args)
end,
ok;
true ->
ok
end.
get_header("default") ->
io_lib:format("\n-----------------------------"
"-----------------------\n~s\n",
[log_timestamp(?now)]);
get_header(Heading) ->
io_lib:format("\n-----------------------------"
"-----------------------\n~ts ~s\n",
[Heading,log_timestamp(?now)]).
%%%-----------------------------------------------------------------
%%% -spec tc_pal(Category,Format,Args) -> ok
%%% Equivalent to tc_pal(Category,?STD_IMPORTANCE,Format,Args,[]) -> ok
tc_pal(Category,Format,Args) ->
tc_pal(Category,?STD_IMPORTANCE,Format,Args,[]).
%%%-----------------------------------------------------------------
%%% -spec tc_pal(Category,Importance,Format,Args) -> ok
%%% Equivalent to tc_pal(Category,Importance,Format,Args,[]) -> ok
tc_pal(Category,Importance,Format,Args) ->
tc_pal(Category,Importance,Format,Args,[]).
%%%-----------------------------------------------------------------
%%% -spec tc_pal(Category,Importance,Format,Args,Opts) -> ok
%%% Category = atom()
%%% Importance = integer()
%%% Format = string()
%%% Args = list()
%%% Opts = list()
%%%
%%% Print and log from a testcase.
%%%
%%% This function is called by ct when logging
%%% stuff directly from a testcase. The info is written both in the
%%% log and on the console.
tc_pal(Category,Importance,Format,Args,Opts) ->
tc_print(Category,Importance,Format,Args,Opts),
tc_log(Category,Importance,"User",Format,Args,[esc_chars|Opts]).
%%%-----------------------------------------------------------------
%%% -spec ct_log(Category,Format,Args) -> ok
%%% Category = atom()
%%% Format = string()
%%% Args = list()
%%%
%%% Print to the ct framework log
%%%
%%% This function is called by internal ct functions to
%%% force logging to the ct framework log
ct_log(Category,Format,Args) ->
cast({ct_log,[{hd,div_header(Category),[]},
{Format,Args},
{ft,div_footer(),[]}],
true}),
ok.
%%%=================================================================
%%% Internal functions
int_header() ->
"</pre>\n<div class=\"ct_internal\"><pre><b>*** CT ~s *** ~ts</b>".
int_footer() ->
"</pre></div>\n<pre>".
div_header(Class) ->
div_header(Class,"User").
div_header(Class,Heading) ->
"\n</pre>\n<div class=\"" ++ atom_to_list(Class) ++ "\"><pre><b>*** "
++ Heading ++ " " ++ log_timestamp(?now) ++ " ***</b>".
div_footer() ->
"</pre></div>\n<pre>".
maybe_log_timestamp() ->
{MS,S,US} = ?now,
case get(log_timestamp) of
{MS,S,_} ->
ok;
_ ->
cast({log,sync,self(),group_leader(),ct_internal,?MAX_IMPORTANCE,
[{hd,"<i>~s</i>",[log_timestamp({MS,S,US})]}],false})
end.
log_timestamp({MS,S,US}) ->
put(log_timestamp, {MS,S,US}),
{{Year,Month,Day}, {Hour,Min,Sec}} =
calendar:now_to_local_time({MS,S,US}),
MilliSec = trunc(US/1000),
lists:flatten(io_lib:format("~4.10.0B-~2.10.0B-~2.10.0B "
"~2.10.0B:~2.10.0B:~2.10.0B.~3.10.0B",
[Year,Month,Day,Hour,Min,Sec,MilliSec])).
%%%-----------------------------------------------------------------
%%% The logger server
-record(logger_state,{parent,
log_dir,
start_time,
orig_GL,
ct_log_fd,
tc_groupleaders,
stylesheet,
async_print_jobs,
tc_esc_chars,
log_index}).
logger(Parent, Mode, Verbosity, CustomStylesheet) ->
register(?MODULE,self()),
ct_util:mark_process(),
%%! Below is a temporary workaround for the limitation of
%%! max one test run per second.
%%! --->
Time0 = calendar:local_time(),
Dir0 = make_dirname(Time0),
{Time,Dir} =
case filelib:is_dir(Dir0) of
true ->
timer:sleep(1000),
Time1 = calendar:local_time(),
Dir1 = make_dirname(Time1),
{Time1,Dir1};
false ->
{Time0,Dir0}
end,
%%! <---
_ = file:make_dir(Dir),
AbsDir = ?abs(Dir),
put(ct_run_dir, AbsDir),
case basic_html() of
true ->
put(basic_html, true);
BasicHtml ->
put(basic_html, BasicHtml),
%% copy stylesheet to log dir (both top dir and test run
%% dir) so logs are independent of Common Test installation
{ok,Cwd} = file:get_cwd(),
CTPath = code:lib_dir(common_test),
PrivFiles = [?css_default,?jquery_script,?tablesorter_script],
PrivFilesSrc = [filename:join(filename:join(CTPath, "priv"), F) ||
F <- PrivFiles],
PrivFilesDestTop = [filename:join(Cwd, F) || F <- PrivFiles],
PrivFilesDestRun = [filename:join(AbsDir, F) || F <- PrivFiles],
case copy_priv_files(PrivFilesSrc, PrivFilesDestTop) of
{error,Src1,Dest1,Reason1} ->
io:format(?def_gl, "ERROR! "++
"Priv file ~tp could not be copied to ~tp. "++
"Reason: ~tp~n",
[Src1,Dest1,Reason1]),
exit({priv_file_error,Dest1});
ok ->
case copy_priv_files(PrivFilesSrc, PrivFilesDestRun) of
{error,Src2,Dest2,Reason2} ->
io:format(?def_gl,
"ERROR! "++
"Priv file ~tp could not be copied to ~tp. "
++"Reason: ~tp~n",
[Src2,Dest2,Reason2]),
exit({priv_file_error,Dest2});
ok ->
ok
end
end
end,
_ = test_server_io:start_link(),
MiscIoName = filename:join(Dir, ?misc_io_log),
{ok,MiscIoFd} = file:open(MiscIoName,
[write,{encoding,utf8}]),
test_server_io:set_fd(unexpected_io, MiscIoFd),
{MiscIoHeader,MiscIoFooter} =
case get_ts_html_wrapper("Pre/post-test I/O log", Dir, false,
Dir, undefined, utf8, CustomStylesheet) of
{basic_html,UH,UF} ->
{UH,UF};
{xhtml,UH,UF} ->
{UH,UF}
end,
io:put_chars(MiscIoFd,
[MiscIoHeader,
"<a name=\"pretest\"></a>\n",
xhtml("<br>\n<h2>Pre-test Log</h2>",
"<br />\n<h3>PRE-TEST LOG</h3>"),
"\n<pre>\n"]),
MiscIoDivider =
"\n<a name=\"posttest\"></a>\n"++
xhtml("</pre>\n<br><h2>Post-test Log</h2>\n<pre>\n",
"</pre>\n<br />\n<h3>POST-TEST LOG</h3>\n<pre>\n"),
ct_util:set_testdata_async({misc_io_log,{filename:absname(MiscIoName),
MiscIoDivider,MiscIoFooter}}),
ct_event:notify(#event{name=start_logging,node=node(),
data=AbsDir}),
make_all_runs_index(start, CustomStylesheet),
_ = make_all_suites_index(start, CustomStylesheet),
case Mode of
interactive -> interactive_link();
_ -> ok
end,
ok = file:set_cwd(Dir),
_ = make_last_run_index(Time, CustomStylesheet),
CtLogFd = open_ctlog(?misc_io_log, CustomStylesheet),
io:format(CtLogFd,int_header()++int_footer(),
[log_timestamp(?now),"Common Test Logger started"]),
Parent ! {started,self(),{Time,filename:absname("")}},
set_evmgr_gl(CtLogFd),
%% save verbosity levels in dictionary for fast lookups
io:format(CtLogFd, "\nVERBOSITY LEVELS:\n", []),
case proplists:get_value('$unspecified', Verbosity) of
undefined -> ok;
GenLvl -> io:format(CtLogFd, "~-25s~3w~n",
["general level",GenLvl])
end,
_ = [begin put({verbosity,Cat},VLvl),
if Cat == '$unspecified' ->
ok;
true ->
io:format(CtLogFd, "~-25w~3w~n", [Cat,VLvl])
end
end || {Cat,VLvl} <- Verbosity],
io:nl(CtLogFd),
TcEscChars = case application:get_env(common_test, esc_chars) of
{ok,ECBool} -> ECBool;
_ -> true
end,
logger_loop(#logger_state{parent=Parent,
log_dir=AbsDir,
start_time=Time,
orig_GL=group_leader(),
ct_log_fd=CtLogFd,
tc_groupleaders=[],
async_print_jobs=[],
tc_esc_chars=TcEscChars,
stylesheet=CustomStylesheet,
log_index=1}).
copy_priv_files([SrcF | SrcFs], [DestF | DestFs]) ->
case file:copy(SrcF, DestF) of
{error,Reason} ->
{error,SrcF,DestF,Reason};
_ ->
copy_priv_files(SrcFs, DestFs)
end;
copy_priv_files([], []) ->
ok.
logger_loop(State) ->
receive
{log,SyncOrAsync,Pid,GL,Category,Importance,Content,EscChars} ->
VLvl = case Category of
ct_internal ->
?MAX_VERBOSITY;
_ ->
case get({verbosity,Category}) of
undefined -> get({verbosity,'$unspecified'});
Val -> Val
end
end,
if Importance >= (100-VLvl) ->
CtLogFd = State#logger_state.ct_log_fd,
DoEscChars = State#logger_state.tc_esc_chars and EscChars,
case get_groupleader(Pid, GL, State) of
{tc_log,TCGL,TCGLs} ->
case erlang:is_process_alive(TCGL) of
true ->
State1 = print_to_log(SyncOrAsync, Pid,
Category, TCGL, Content,
DoEscChars, State),
logger_loop(State1#logger_state{
tc_groupleaders = TCGLs});
false ->
%% Group leader is dead, so write to the
%% CtLog or unexpected_io log instead
unexpected_io(Pid, Category, Importance,
Content, CtLogFd, DoEscChars),
logger_loop(State)
end;
{ct_log,_Fd,TCGLs} ->
%% If category is ct_internal then write
%% to ct_log, else write to unexpected_io
%% log
unexpected_io(Pid, Category, Importance, Content,
CtLogFd, DoEscChars),
logger_loop(State#logger_state{
tc_groupleaders = TCGLs})
end;
true ->
logger_loop(State)
end;
{{init_tc,TCPid,GL,RefreshLog},From} ->
%% make sure no IO for this test case from the
%% CT logger gets rejected
test_server:permit_io(GL, self()),
IoFormat = fun tc_io_format/3,
print_style(GL, IoFormat, State#logger_state.stylesheet),
set_evmgr_gl(GL),
TCGLs = add_tc_gl(TCPid,GL,State),
_ = if not RefreshLog ->
ok;
true ->
make_last_run_index(State#logger_state.start_time, State#logger_state.stylesheet)
end,
return(From,ok),
logger_loop(State#logger_state{tc_groupleaders = TCGLs});
{{end_tc,TCPid},From} ->
set_evmgr_gl(State#logger_state.ct_log_fd),
return(From,ok),
logger_loop(State#logger_state{tc_groupleaders =
rm_tc_gl(TCPid,State)});
{{register_groupleader,Pid,GL},From} ->
GLs = add_tc_gl(Pid,GL,State),
return(From,ok),
logger_loop(State#logger_state{tc_groupleaders = GLs});
{{unregister_groupleader,Pid},From} ->
return(From,ok),
logger_loop(State#logger_state{tc_groupleaders =
rm_tc_gl(Pid,State)});
{{get_log_dir,true},From} ->
return(From,{ok,State#logger_state.log_dir}),
logger_loop(State);
{{get_log_dir,false},From} ->
return(From,{ok,filename:basename(State#logger_state.log_dir)}),
logger_loop(State);
{make_last_run_index,From} ->
_ = make_last_run_index(State#logger_state.start_time, State#logger_state.stylesheet),
return(From,get(ct_log_cache)),
logger_loop(State);
{get_stylesheet, From} ->
return(From, State#logger_state.stylesheet),
logger_loop(State);
{set_stylesheet,_,SSFile} when State#logger_state.stylesheet ==
SSFile ->
logger_loop(State);
{set_stylesheet,TC,SSFile} ->
Fd = State#logger_state.ct_log_fd,
io:format(Fd, "~tp loading external style sheet: ~ts~n",
[TC,SSFile]),
logger_loop(State#logger_state{stylesheet = SSFile});
{clear_stylesheet,_} when State#logger_state.stylesheet == undefined ->
logger_loop(State);
{clear_stylesheet,_} ->
logger_loop(State#logger_state{stylesheet = undefined});
{ct_log,Content,EscChars} ->
Str = lists:map(fun({_HdOrFt,Str,Args}) ->
[io_lib:format(Str,Args),io_lib:nl()];
({Str,Args}) when EscChars ->
Io = io_lib:format(Str,Args),
[escape_chars(Io),io_lib:nl()];
({Str,Args}) ->
[io_lib:format(Str,Args),io_lib:nl()]
end, Content),
Fd = State#logger_state.ct_log_fd,
io:format(Fd, "~ts", [Str]),
logger_loop(State);
{'DOWN',Ref,_,_Pid,_} ->
%% there might be print jobs executing in parallel with ct_logs
%% and whenever one is finished (indicated by 'DOWN'), the
%% next job should be spawned
case lists:delete(Ref, State#logger_state.async_print_jobs) of
[] ->
logger_loop(State#logger_state{async_print_jobs = []});
Jobs ->
[Next|JobsRev] = lists:reverse(Jobs),
Jobs1 = [print_next(Next)|lists:reverse(JobsRev)],
logger_loop(State#logger_state{async_print_jobs = Jobs1})
end;
stop ->
io:format(State#logger_state.ct_log_fd,
int_header()++int_footer(),
[log_timestamp(?now),"Common Test Logger finished"]),
close_ctlog(State#logger_state.ct_log_fd),
ok
end.
create_io_fun(FromPid, CtLogFd, EscChars) ->
create_io_fun(FromPid, CtLogFd, EscChars, undefined).
create_io_fun(FromPid, CtLogFd, EscChars, LogIndex) ->
%% we have to build one io-list of all strings
%% before printing, or other io printouts (made in
%% parallel) may get printed between this header
%% and footer
fun(FormatData, IoList) ->
{Escapable,AddAnchor,Str,Args} =
case FormatData of
{hd,S,A} -> {false,true,S,A};
{_ft,S,A} -> {false,false,S,A};
{S,A} -> {true,false,S,A}
end,
try io_lib:format(lists:flatten(Str), Args) of
IoStr when Escapable, EscChars, IoList == [] ->
escape_chars(IoStr);
IoStr when Escapable, EscChars ->
[IoList,"\n",escape_chars(IoStr)];
IoStr when IoList == [] ->
IoStr++[anchor_link(LogIndex) || AddAnchor];
IoStr ->
[IoList,"\n",IoStr]++[anchor_link(LogIndex) || AddAnchor]
catch
_:_Reason ->
io:format(CtLogFd, "Logging fails! Str: ~tp, Args: ~tp~n",
[Str,Args]),
%% stop the testcase, we need to see the fault
exit(FromPid, {log_printout_error,Str,Args}),
[]
end
end.
anchor_link(undefined) ->
[];
anchor_link(LogIndex) ->
IdLink = ["e-", integer_to_list(LogIndex)],
["<a id=", IdLink, " class=\"link-to-entry\" ",
"href=\"#", IdLink, "\">🔗</a>"].
escape_chars([Bin | Io]) when is_binary(Bin) ->
[Bin | escape_chars(Io)];
escape_chars([List | Io]) when is_list(List) ->
[escape_chars(List) | escape_chars(Io)];
escape_chars([$< | Io]) ->
["<" | escape_chars(Io)];
escape_chars([$> | Io]) ->
[">" | escape_chars(Io)];
escape_chars([$& | Io]) ->
["&" | escape_chars(Io)];
escape_chars([Char | Io]) when is_integer(Char) ->
[Char | escape_chars(Io)];
escape_chars([]) ->
[];
escape_chars(Bin) ->
Bin.
print_to_log(sync, FromPid, Category, TCGL, Content, EscChars,
#logger_state{log_index=LogIndex}=State) ->
%% in some situations (exceptions), the printout is made from the
%% test server IO process and there's no valid group leader to send to