File: test_logging.cc

package info (click to toggle)
mysql-8.0 8.0.43-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,924 kB
  • sloc: cpp: 4,684,605; ansic: 412,450; pascal: 108,398; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; sh: 24,181; python: 21,816; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,076; makefile: 2,194; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (3314 lines) | stat: -rw-r--r-- 132,710 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
/*
  Copyright (c) 2017, 2025, Oracle and/or its affiliates.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License, version 2.0,
  as published by the Free Software Foundation.

  This program is designed to work with certain software (including
  but not limited to OpenSSL) that is licensed under separate terms,
  as designated in a particular file or component or in included license
  documentation.  The authors of MySQL hereby grant you an additional
  permission to link the program and your derivative works with the
  separately licensed software that they have either included with
  the program or referenced in the documentation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <condition_variable>
#include <csignal>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <mutex>
#include <string>
#include <thread>

#include <gmock/gmock-matchers.h>
#include <gtest/gtest.h>

#include "config_builder.h"
#include "dim.h"
#include "mock_server_rest_client.h"
#include "mock_server_testutils.h"
#include "mysql/harness/logging/logging.h"
#include "mysql/harness/string_utils.h"  // split_string
#include "mysqlrouter/mysql_session.h"
#include "mysqlrouter/utils.h"  // rename_file
#include "process_wrapper.h"
#include "random_generator.h"
#include "router_component_test.h"
#include "router_component_testutils.h"
#include "router_config.h"
#include "router_test_helpers.h"  // get_file_output
#include "tcp_port_pool.h"

/**
 * @file
 * @brief Component Tests for loggers
 */

using mysql_harness::logging::LogLevel;
using mysql_harness::logging::LogTimestampPrecision;
using testing::HasSubstr;
using testing::Not;
using testing::StartsWith;
using namespace std::chrono_literals;
using namespace std::string_literals;

class RouterLoggingTest : public RouterComponentBootstrapTest {
 protected:
  std::string create_config_file(
      const std::string &directory, const std::string &sections,
      const std::map<std::string, std::string> *default_section) const {
    return ProcessManager::create_config_file(
        directory, sections, default_section, "mysqlrouter.conf", "", false);
  }

  ProcessWrapper &launch_router_for_fail(
      const std::vector<std::string> &params) {
    return launch_router(
        params, EXIT_FAILURE, true, false, -1s,
        RouterComponentBootstrapTest::kBootstrapOutputResponder);
  }

  ProcessWrapper &launch_router_for_success(
      const std::vector<std::string> &params) {
    return launch_router(params, EXIT_SUCCESS, true);
  }
};

/** @test Check that the Router logs its version when it is started and stopped
 */
TEST_F(RouterLoggingTest, log_start_stop_with_version) {
  // create tmp dir where we will log
  TempDirectory logging_folder;

  std::map<std::string, std::string> params = get_DEFAULT_defaults();
  params.at("logging_folder") = logging_folder.name();
  TempDirectory conf_dir("conf");
  const std::string conf_file =
      create_config_file(conf_dir.name(), "[keepalive]", &params);

  // run the router and close right away
  auto &router = launch_router_for_success({"-c", conf_file});
  router.send_shutdown_event();
  router.wait_for_exit();

  auto file_content =
      router.get_logfile_content("mysqlrouter.log", logging_folder.name());
  auto lines = mysql_harness::split_string(file_content, '\n');

#if defined(_WIN32)
  const std::string stopping_info = "";
#elif defined(__APPLE__)
  const std::string stopping_info = " \\(Signal .*\\)";
#else
  const std::string stopping_info =
      " \\(Signal .* sent by UID: .* and PID: .*\\)";
#endif

  EXPECT_THAT(
      file_content,
      ::testing::AllOf(
          ::testing::ContainsRegex(
              "main SYSTEM .* Starting 'MySQL Router', version: "s +
              MYSQL_ROUTER_VERSION + " \\(" + MYSQL_ROUTER_VERSION_EDITION +
              "\\)"),
          ::testing::ContainsRegex(
              "main SYSTEM .* Stopping 'MySQL Router', version: "s +
              MYSQL_ROUTER_VERSION + " \\(" + MYSQL_ROUTER_VERSION_EDITION +
              "\\), reason: REQUESTED" + stopping_info)));
}

/** @test This test verifies that fatal error messages thrown before switching
 * to logger specified in config file (before Loader::run() runs
 * logger_plugin.cc:init()) are properly logged to STDERR
 */
TEST_F(RouterLoggingTest, log_startup_failure_to_console) {
  auto conf_params = get_DEFAULT_defaults();
  // we want to log to the console
  conf_params["logging_folder"] = "";
  TempDirectory conf_dir("conf");
  const std::string conf_file =
      create_config_file(conf_dir.name(), "[invalid]", &conf_params);

  // run the router and wait for it to exit
  auto &router = launch_router_for_fail({"-c", conf_file});
  check_exit_code(router, EXIT_FAILURE);

  // expect something like this to appear on STDERR
  // plugin 'invalid' failed to
  // load: ./plugin_output_directory/invalid.so: cannot open shared object
  // file: No such file or directory
  const std::string out = router.get_full_output();
  EXPECT_THAT(
      out, HasSubstr("Loading plugin for config-section '[invalid]' failed"));
}

/** @test This test is similar to log_startup_failure_to_console(), but the
 * failure message is expected to be logged into a logfile
 */
TEST_F(RouterLoggingTest, log_startup_failure_to_logfile) {
  // create tmp dir where we will log
  TempDirectory logging_folder;

  // create config with logging_folder set to that directory
  std::map<std::string, std::string> params = get_DEFAULT_defaults();
  params.at("logging_folder") = logging_folder.name();
  TempDirectory conf_dir("conf");
  const std::string conf_file =
      create_config_file(conf_dir.name(), "[routing]", &params);

  // run the router and wait for it to exit
  auto &router = launch_router_for_fail({"-c", conf_file});
  check_exit_code(router, EXIT_FAILURE);

  // expect something like this to appear in log:
  // 2018-12-19 03:54:04 main ERROR [7f539f628780] Configuration error: option
  // destinations in [routing] is required
  auto file_content =
      router.get_logfile_content("mysqlrouter.log", logging_folder.name());
  auto lines = mysql_harness::split_string(file_content, '\n');

  EXPECT_THAT(lines,
              ::testing::Contains(::testing::HasSubstr(
                  "Configuration error: option destinations in [routing] is "
                  "required")));
}

/** @test This test verifies that invalid logging_folder is properly handled and
 * appropriate message is printed on STDERR. Router tries to
 * mkdir(logging_folder) if it doesn't exist, then write its log inside of it.
 */
TEST_F(RouterLoggingTest, bad_logging_folder) {
  // create tmp dir to contain our tests
  TempDirectory tmp_dir;

// unfortunately it's not (reasonably) possible to make folders read-only on
// Windows, therefore we can run the following 2 tests only on Unix
// https://support.microsoft.com/en-us/help/326549/you-cannot-view-or-change-the-read-only-or-the-system-attributes-of-fo
#ifndef _WIN32

  // make tmp dir read-only
  chmod(tmp_dir.name().c_str(),
        S_IRUSR | S_IXUSR);  // r-x for the user (aka 500)

  // logging_folder doesn't exist and can't be created
  {
    const std::string logging_dir = tmp_dir.name() + "/some_dir";

    // create Router config
    std::map<std::string, std::string> params = get_DEFAULT_defaults();
    params.at("logging_folder") = logging_dir;
    TempDirectory conf_dir("conf");
    const std::string conf_file =
        create_config_file(conf_dir.name(), "[keepalive]\n", &params);

    // run the router and wait for it to exit
    auto &router = launch_router_for_fail({"-c", conf_file});
    check_exit_code(router, EXIT_FAILURE);

    // expect something like this to appear on STDERR
    // Error: Error when creating dir '/bla': 13
    const std::string out = router.get_full_output();
    EXPECT_THAT(out.c_str(),
                HasSubstr("  init 'logger' failed: Error when creating dir '" +
                          logging_dir + "': 13"));
  }

  // logging_folder exists but is not writeable
  {
    const std::string logging_dir = tmp_dir.name();

    // create Router config
    std::map<std::string, std::string> params = get_DEFAULT_defaults();
    params.at("logging_folder") = logging_dir;
    TempDirectory conf_dir("conf");
    const std::string conf_file =
        create_config_file(conf_dir.name(), "[keepalive]\n", &params);

    // run the router and wait for it to exit
    auto &router = launch_router_for_fail({"-c", conf_file});
    check_exit_code(router, EXIT_FAILURE);

    // expect something like this to appear on STDERR
    // Error: Cannot create file in directory //mysqlrouter.log: Permission
    // denied
    const std::string out = router.get_full_output();
#ifndef _WIN32
    EXPECT_THAT(
        out.c_str(),
        HasSubstr("  init 'logger' failed: Cannot create file in directory " +
                  logging_dir + ": Permission denied\n"));
#endif
  }

  // restore writability to tmp dir
  chmod(tmp_dir.name().c_str(),
        S_IRUSR | S_IWUSR | S_IXUSR);  // rwx for the user (aka 700)

#endif  // #ifndef _WIN32

  // logging_folder is really a file
  {
    const std::string logging_dir = tmp_dir.name() + "/some_file";

    // create that file
    {
      std::ofstream some_file(logging_dir);
      EXPECT_TRUE(some_file.good());
    }

    // create Router config
    std::map<std::string, std::string> params = get_DEFAULT_defaults();
    params.at("logging_folder") = logging_dir;
    TempDirectory conf_dir("conf");
    const std::string conf_file =
        create_config_file(conf_dir.name(), "[keepalive]\n", &params);

    // run the router and wait for it to exit
    auto &router = launch_router_for_fail({"-c", conf_file});
    check_exit_code(router, EXIT_FAILURE);

    // expect something like this to appear on STDERR
    // Error: Cannot create file in directory /etc/passwd/mysqlrouter.log: Not a
    // directory
    const std::string out = router.get_full_output();
    const std::string prefix("Cannot create file in directory " + logging_dir +
                             ": ");
#ifndef _WIN32
    EXPECT_THAT(out.c_str(), HasSubstr(prefix + "Not a directory\n"));
#else
    // on Windows emulate (wine) we get ENOTDIR
    // with native windows we get ENOENT

    EXPECT_THAT(
        out.c_str(),
        ::testing::AnyOf(
            ::testing::HasSubstr(prefix + "Directory name invalid.\n"),
            ::testing::HasSubstr(
                prefix + "The system cannot find the path specified.\n")));
#endif
  }
}

TEST_F(RouterLoggingTest, multiple_logger_sections) {
  // This test verifies that multiple [logger] sections are handled properly.
  // Router should report the error on STDERR and exit

  auto conf_params = get_DEFAULT_defaults();
  // we want to log to the console
  conf_params["logging_folder"] = "";
  TempDirectory conf_dir("conf");
  const std::string conf_file =
      create_config_file(conf_dir.name(), "[logger]\n[logger]\n", &conf_params);

  // run the router and wait for it to exit
  auto &router = launch_router_for_fail({"-c", conf_file});
  check_exit_code(router, EXIT_FAILURE);

  // expect something like this to appear on STDERR
  // Error: Configuration error: Section 'logger' already exists
  const std::string out = router.get_full_output();
  EXPECT_THAT(
      out.c_str(),
      ::testing::HasSubstr(
          "Error: Configuration error: Section 'logger' already exists"));
}

TEST_F(RouterLoggingTest, logger_section_with_key) {
  // This test verifies that [logger:with_some_key] section is handled properly
  // Router should report the error on STDERR and exit
  auto conf_params = get_DEFAULT_defaults();
  // we want to log to the console
  conf_params["logging_folder"] = "";
  TempDirectory conf_dir("conf");
  const std::string conf_file =
      create_config_file(conf_dir.name(), "[logger:some_key]\n", &conf_params);

  // run the router and wait for it to exit
  auto &router = launch_router_for_fail({"-c", conf_file});
  check_exit_code(router, EXIT_FAILURE);

  // expect something like this to appear on STDERR
  // Error: Section 'logger' does not support key
  const std::string out = router.get_full_output();
  EXPECT_THAT(out.c_str(),
              HasSubstr("Error: Section 'logger' does not support keys"));
}

TEST_F(RouterLoggingTest, bad_loglevel) {
  // This test verifies that bad log level in [logger] section is handled
  // properly. Router should report the error on STDERR and exit

  auto conf_params = get_DEFAULT_defaults();
  // we want to log to the console
  conf_params["logging_folder"] = "";
  TempDirectory conf_dir("conf");
  const std::string conf_file = create_config_file(
      conf_dir.name(), "[logger]\nlevel = UNKNOWN\n", &conf_params);

  // run the router and wait for it to exit
  auto &router = launch_router_for_fail({"-c", conf_file});
  check_exit_code(router, EXIT_FAILURE);

  // expect something like this to appear on STDERR
  // Configuration error: Log level 'unknown' is not valid. Valid values are:
  // fatal, system, error, warning, info, note, and debug
  const std::string out = router.get_full_output();
  EXPECT_THAT(
      out.c_str(),
      HasSubstr(
          "Configuration error: Log level 'unknown' is not valid. Valid "
          "values are: fatal, system, error, warning, info, note, and debug"));
}

/**************************************************/
/* Tests for valid logger configurations          */
/**************************************************/

struct LoggingConfigOkParams {
  const char *test_name;

  std::string logger_config;
  bool logging_folder_empty;

  LogLevel consolelog_expected_level;
  LogLevel filelog_expected_level;

  LogTimestampPrecision consolelog_expected_timestamp_precision;
  LogTimestampPrecision filelog_expected_timestamp_precision;

  LoggingConfigOkParams(const char *test_name_,
                        const std::string &logger_config_,
                        const bool logging_folder_empty_,
                        const LogLevel consolelog_expected_level_,
                        const LogLevel filelog_expected_level_)
      : test_name{test_name_},
        logger_config(logger_config_),
        logging_folder_empty(logging_folder_empty_),
        consolelog_expected_level(consolelog_expected_level_),
        filelog_expected_level(filelog_expected_level_),
        consolelog_expected_timestamp_precision(LogTimestampPrecision::kNotSet),
        filelog_expected_timestamp_precision(LogTimestampPrecision::kNotSet) {}

  LoggingConfigOkParams(
      const char *test_name_, const std::string &logger_config_,
      const bool logging_folder_empty_,
      const LogLevel consolelog_expected_level_,
      const LogLevel filelog_expected_level_,
      const LogTimestampPrecision consolelog_expected_timestamp_precision_,
      const LogTimestampPrecision filelog_expected_timestamp_precision_)
      : test_name{test_name_},
        logger_config(logger_config_),
        logging_folder_empty(logging_folder_empty_),
        consolelog_expected_level(consolelog_expected_level_),
        filelog_expected_level(filelog_expected_level_),
        consolelog_expected_timestamp_precision(
            consolelog_expected_timestamp_precision_),
        filelog_expected_timestamp_precision(
            filelog_expected_timestamp_precision_) {}
};

::std::ostream &operator<<(::std::ostream &os,
                           const LoggingConfigOkParams &ltp) {
  return os << "config=" << ltp.logger_config
            << ", logging_folder_empty=" << ltp.logging_folder_empty;
}

class RouterLoggingTestConfig
    : public RouterLoggingTest,
      public ::testing::WithParamInterface<LoggingConfigOkParams> {};

/** @test This test verifies that a proper loggs are written to selected sinks
 * for various sinks/levels combinations.
 */
TEST_P(RouterLoggingTestConfig, check) {
  auto test_params = GetParam();

  TempDirectory tmp_dir;

  // These are different level log entries that are expected to get logged after
  // the logger plugin has been initialized
  const std::string kDebugLogEntry = "I'm a debug message";
  const std::string kInfoLogEntry = "I'm an info message";
  const std::string kWarningLogEntry = "I'm a warning message";
  const std::string kNoteLogEntry = "I'm a note message";
  const std::string kSystemLogEntry = "I'm a system message";

  // trigger all messages once.
  const std::string kOtherPluginConfig = "[routertestplugin_logger]\n";

  auto conf_params = get_DEFAULT_defaults();
  conf_params["logging_folder"] =
      test_params.logging_folder_empty ? "" : tmp_dir.name();

  TempDirectory conf_dir("conf");
  const std::string conf_text =
      test_params.logger_config + "\n" + kOtherPluginConfig;

  const std::string conf_file =
      create_config_file(conf_dir.name(), conf_text, &conf_params);

  // use the parent's "launch_router" to wait for NOTIFY_SOCKET
  auto &router = ProcessManager::launch_router({"-c", conf_file});

  SCOPED_TRACE("// stop router to ensure all logs are written");
  router.send_clean_shutdown_event();
  try {
    EXPECT_EQ(router.wait_for_exit(), EXIT_SUCCESS);
  } catch (const std::exception &e) {
    FAIL() << e.what();
  }

  const std::string console_log_txt = router.get_full_output();

  // check the console log if it contains what's expected
  if (test_params.consolelog_expected_level >= LogLevel::kDebug &&
      test_params.consolelog_expected_level != LogLevel::kNotSet) {
    EXPECT_THAT(console_log_txt, HasSubstr(kDebugLogEntry)) << "console:\n"
                                                            << console_log_txt;
  } else {
    EXPECT_THAT(console_log_txt, Not(HasSubstr(kDebugLogEntry)))
        << "console:\n"
        << console_log_txt;
  }

  if (test_params.consolelog_expected_level >= LogLevel::kNote &&
      test_params.consolelog_expected_level != LogLevel::kNotSet) {
    EXPECT_THAT(console_log_txt, HasSubstr(kNoteLogEntry)) << "console:\n"
                                                           << console_log_txt;
  } else {
    EXPECT_THAT(console_log_txt, Not(HasSubstr(kNoteLogEntry)))
        << "console:\n"
        << console_log_txt;
  }

  if (test_params.consolelog_expected_level >= LogLevel::kInfo &&
      test_params.consolelog_expected_level != LogLevel::kNotSet) {
    EXPECT_THAT(console_log_txt, HasSubstr(kInfoLogEntry)) << "console:\n"
                                                           << console_log_txt;
  } else {
    EXPECT_THAT(console_log_txt, Not(HasSubstr(kInfoLogEntry)))
        << "console:\n"
        << console_log_txt;
  }

  if (test_params.consolelog_expected_level >= LogLevel::kWarning &&
      test_params.consolelog_expected_level != LogLevel::kNotSet) {
    EXPECT_THAT(console_log_txt, HasSubstr(kWarningLogEntry))
        << "console:\n"
        << console_log_txt;
  } else {
    EXPECT_THAT(console_log_txt, Not(HasSubstr(kWarningLogEntry)))
        << "console:\n"
        << console_log_txt;
  }

  if (test_params.consolelog_expected_level >= LogLevel::kSystem &&
      test_params.consolelog_expected_level != LogLevel::kNotSet) {
    // No SYSTEM output from Router today, so disable until Router does
    EXPECT_THAT(console_log_txt, HasSubstr(kSystemLogEntry)) << "console:\n"
                                                             << console_log_txt;
  } else {
    // No SYSTEM output from Router today, so disable until Router does
    EXPECT_THAT(console_log_txt, Not(HasSubstr(kSystemLogEntry)))
        << "console:\n"
        << console_log_txt;
  }

  // check the file log if it contains what's expected
  const std::string file_log_txt =
      router.get_logfile_content("mysqlrouter.log", tmp_dir.name());

  if (test_params.filelog_expected_level >= LogLevel::kDebug &&
      test_params.filelog_expected_level != LogLevel::kNotSet) {
    EXPECT_THAT(file_log_txt, HasSubstr(kDebugLogEntry))
        << "file:\n"
        << file_log_txt << "\nconsole:\n"
        << console_log_txt;
  } else {
    EXPECT_THAT(file_log_txt, Not(HasSubstr(kDebugLogEntry)))
        << "file:\n"
        << file_log_txt << "\nconsole:\n"
        << console_log_txt;
  }

  if (test_params.filelog_expected_level >= LogLevel::kNote &&
      test_params.filelog_expected_level != LogLevel::kNotSet) {
    EXPECT_THAT(file_log_txt, HasSubstr(kNoteLogEntry))
        << "file:\n"
        << file_log_txt << "\nconsole:\n"
        << console_log_txt;
  } else {
    EXPECT_THAT(file_log_txt, Not(HasSubstr(kNoteLogEntry)))
        << "file:\n"
        << file_log_txt << "\nconsole:\n"
        << console_log_txt;
  }

  if (test_params.filelog_expected_level >= LogLevel::kInfo &&
      test_params.filelog_expected_level != LogLevel::kNotSet) {
    EXPECT_THAT(file_log_txt, HasSubstr(kInfoLogEntry))
        << "file:\n"
        << file_log_txt << "\nconsole:\n"
        << console_log_txt;
  } else {
    EXPECT_THAT(file_log_txt, Not(HasSubstr(kInfoLogEntry)))
        << "file:\n"
        << file_log_txt << "\nconsole:\n"
        << console_log_txt;
  }

  if (test_params.filelog_expected_level >= LogLevel::kWarning &&
      test_params.filelog_expected_level != LogLevel::kNotSet) {
    EXPECT_THAT(file_log_txt, HasSubstr(kWarningLogEntry))
        << "file:\n"
        << file_log_txt << "\nconsole:\n"
        << console_log_txt;
  } else {
    EXPECT_THAT(file_log_txt, Not(HasSubstr(kWarningLogEntry)))
        << "file:\n"
        << file_log_txt << "\nconsole:\n"
        << console_log_txt;
  }

  if (test_params.filelog_expected_level >= LogLevel::kSystem &&
      test_params.filelog_expected_level != LogLevel::kNotSet) {
    EXPECT_THAT(file_log_txt, HasSubstr(kSystemLogEntry))
        << "file:\n"
        << file_log_txt << "\nconsole:\n"
        << console_log_txt;
  } else {
    EXPECT_THAT(file_log_txt, Not(HasSubstr(kSystemLogEntry)))
        << "file:\n"
        << file_log_txt << "\nconsole:\n"
        << console_log_txt;
  }
}

INSTANTIATE_TEST_SUITE_P(
    Spec, RouterLoggingTestConfig,
    ::testing::Values(
        // no logger section, no sinks sections
        // logging_folder not empty so we are expected to log to the file
        // with a warning level so info and debug logs will not be there
        LoggingConfigOkParams(
            "no_logger_section_no_sinks_no_logger_folder",  // testname
            "",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kWarning),

        // no logger section, no sinks sections
        // logging_folder empty so we are expected to log to the console
        // with a warning level so info and debug logs will not be there
        LoggingConfigOkParams(
            "no_logger_section_no_sinks",  // testname
            "",
            /* logging_folder_empty = */ true,
            /* consolelog_expected_level =  */ LogLevel::kWarning,
            /* filelog_expected_level =  */ LogLevel::kNotSet),

        // logger section, no sinks sections
        // logging_folder not empty so we are expected to log to the file
        // with a warning level as level is not redefined in the [logger]
        // section
        LoggingConfigOkParams(
            "logger_section_only",  // testname
            "[logger]",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kWarning),

        // logger section, no sinks sections
        // logging_folder not empty so we are expected to log to the file
        // with a level defined in the logger section
        LoggingConfigOkParams(
            "no_sinks",  // testname
            "[logger]\n"
            "level=info\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kInfo),

        // logger section, no sinks sections; logging_folder is empty so we are
        // expected to log to the console with a level defined in the logger
        // section
        LoggingConfigOkParams(
            "no_sinks_no_logger_folder",  // testname
            "[logger]\n"
            "level=info\n",
            /* logging_folder_empty = */ true,
            /* consolelog_expected_level =  */ LogLevel::kInfo,
            /* filelog_expected_level =  */ LogLevel::kNotSet),

        // consolelog configured as a sink; it does not have its section in the
        // config but that is not an error; even though the logging folder is
        // not empty, we still don't log to the file as sinks= setting wants use
        // the console
        LoggingConfigOkParams(
            "consolelog",
            "[logger]\n"
            "level=debug\n"
            "sinks=consolelog\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kNotSet),

        // 2 sinks have sections but consolelog is not defined as a sink in the
        // [logger] section so there should be no logging to the console (after
        // [logger] is initialised; prior to that all is logged to the console
        // by default)
        LoggingConfigOkParams(
            "one_sink_ignored",  // testname
            "[logger]\n"
            "sinks=filelog\n"
            "level=debug\n"
            "[filelog]\n"
            "[consolelog]\n"
            "level=debug\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kDebug),

        // 2 sinks, both should inherit log level from [logger] section (which
        // is debug)
        LoggingConfigOkParams(
            "two_sinks_inherit_log_level_debug",  // testname
            "[logger]\n"
            "sinks=filelog,consolelog\n"
            "level=debug\n"
            "[filelog]\n"
            "[consolelog]\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug),

        // 2 sinks, both should inherit log level from [logger] section (which
        // is info); debug logs are not expected for both sinks
        /*8*/
        LoggingConfigOkParams(
            "two_sinks_inherit_log_level_info",  // testname
            "[logger]\n"
            "sinks=filelog,consolelog\n"
            "level=info\n"
            "[filelog]\n"
            "[consolelog]\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kInfo,
            /* filelog_expected_level =  */ LogLevel::kInfo),

        // 2 sinks, both should inherit log level from [logger] section (which
        // is warning); neither debug not info logs are not expected for both
        // sinks
        LoggingConfigOkParams(
            "two_sinks_inherit_warning",  // testname
            "[logger]\n"
            "sinks=filelog,consolelog\n"
            "level=warning\n"
            "[filelog]\n"
            "[consolelog]\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kWarning,
            /* filelog_expected_level =  */ LogLevel::kWarning),

        // 2 sinks, one overwrites the default log level, the other inherits
        // default from [logger] section
        LoggingConfigOkParams(
            "inherit_info_filelog_debug",  // testname
            "[logger]\n"
            "sinks=filelog,consolelog\n"
            "level=info\n"
            "[filelog]\n"
            "level=debug\n"
            "[consolelog]\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kInfo,
            /* filelog_expected_level =  */ LogLevel::kDebug),

        // 2 sinks, each defines its own custom log level that overwrites the
        // default from [logger] section
        LoggingConfigOkParams(
            "default_info_overwrite_debug_warning",  // testname
            "[logger]\n"
            "sinks=filelog,consolelog\n"
            "level=info\n"
            "[filelog]\n"
            "level=debug\n"
            "[consolelog]\n"
            "level=warning\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kWarning,
            /* filelog_expected_level =  */ LogLevel::kDebug),

        // 2 sinks, each defines its own custom log level that overwrites the
        // default from [logger] section
        LoggingConfigOkParams(
            "default_warning_overwrite_info_warning",  // testname
            "[logger]\n"
            "sinks=filelog,consolelog\n"
            "level=warning\n"
            "[filelog]\n"
            "level=info\n"
            "[consolelog]\n"
            "level=warning\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kWarning,
            /* filelog_expected_level =  */ LogLevel::kInfo),

        // 2 sinks, each defines its own custom log level (that is more strict)
        // that overwrites the default from [logger] section
        LoggingConfigOkParams(
            "default_debug_overwrite_info_warning",  // testname
            "[logger]\n"
            "sinks=filelog,consolelog\n"
            "level=debug\n"
            "[filelog]\n"
            "level=info\n"
            "[consolelog]\n"
            "level=warning\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kWarning,
            /* filelog_expected_level =  */ LogLevel::kInfo),

        // 2 sinks,no level in the [logger] section and no level in the sinks
        // sections; default log level should be used (which is warning)
        LoggingConfigOkParams(
            "two_sinks_all_default",  // testname
            "[logger]\n"
            "sinks=filelog,consolelog\n"
            "[filelog]\n"
            "[consolelog]\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kWarning,
            /* filelog_expected_level =  */ LogLevel::kWarning),

        // 2 sinks, level in the [logger] section is warning; it should be
        // used by the sinks as they don't redefine it in their sections
        LoggingConfigOkParams(
            "implicit_sinks_level_warning",  // testname
            "[logger]\n"
            "level=warning\n"
            "sinks=filelog,consolelog\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kWarning,
            /* filelog_expected_level =  */ LogLevel::kWarning),

        // 2 sinks, level in the [logger] section is error; it should be used
        // by the sinks as they don't redefine it in their sections
        LoggingConfigOkParams(
            "implicit_sinks_level_error",  // testname
            "[logger]\n"
            "level=error\n"
            "sinks=filelog,consolelog\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kError,
            /* filelog_expected_level =  */ LogLevel::kError),

        // 2 sinks, no level in the [logger] section, each defines it's own
        // level
        LoggingConfigOkParams(
            "explicit_error_debug",  // testname
            "[logger]\n"
            "sinks=filelog,consolelog\n"
            "[filelog]\n"
            "level=error\n"
            "[consolelog]\n"
            "level=debug\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kError),

        // 2 sinks, no level in the [logger] section, one defines it's own
        // level, the other expected to go with default (warning)
        LoggingConfigOkParams(
            "explicit_implicit_error",  // testname
            "[logger]\n"
            "sinks=filelog,consolelog\n"
            "[filelog]\n"
            "level=error\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kWarning,
            /* filelog_expected_level =  */ LogLevel::kError),
        // level note to filelog sink (TS_FR1_01)
        LoggingConfigOkParams(
            "one_sink_note",  // testname
            "[logger]\n"
            "level=note\n"
            "sinks=filelog\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kNote),
        // note level to filelog sink (TS_FR1_02)
        LoggingConfigOkParams(
            "one_sink_system",  // testname
            "[logger]\n"
            "level=system\n"
            "sinks=filelog\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kSystem)),
    [](auto const &info) { return info.param.test_name; });

#ifndef _WIN32
INSTANTIATE_TEST_SUITE_P(
    LoggingConfigTestUnix, RouterLoggingTestConfig,
    ::testing::Values(
        // We can't reliably check if the syslog logging is working with a
        // component test as this is too operating system intrusive and we are
        // supposed to run on pb2 environment. Let's at least check that this
        // sink type is supported
        // Level note to syslog,filelog (TS_FR1_06)
        LoggingConfigOkParams(
            "0",  // testname
            "[logger]\n"
            "level=note\n"
            "sinks=syslog,filelog\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kNote),
        // Level system to syslog,filelog (TS_FR1_07)
        LoggingConfigOkParams(
            "1",  // testname
            "[logger]\n"
            "level=system\n"
            "sinks=syslog,filelog\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kSystem),
        // All sinks (TS_FR1_08)
        LoggingConfigOkParams(
            "2",  // testname
            "[logger]\n"
            "level=debug\n"
            "sinks=syslog,filelog,consolelog\n"
            "[consolelog]\n"
            "level=note\n"
            "[syslog]\n"
            "level=system\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNote,
            /* filelog_expected_level =  */ LogLevel::kDebug),
        // Verify filename option is disregarded by syslog sink
        LoggingConfigOkParams(
            "3",  // testname
            "[logger]\n"
            "level=note\n"
            "sinks=syslog,filelog\n"
            "[syslog]\n"
            "filename=foo.log",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kNote)),
    [](auto const &info) { return info.param.test_name; });
#else
INSTANTIATE_TEST_SUITE_P(
    LoggingConfigTestWindows, RouterLoggingTestConfig,
    ::testing::Values(
        // We can't reliably check if the eventlog logging is working with a
        // component test as this is too operating system intrusive and also
        // requires admin privileges to setup and we are supposed to run on pb2
        // environment. Let's at least check that this sink type is supported.
        // Level note to eventlog,filelog (TS_FR1_03)
        LoggingConfigOkParams(
            "0",  // testname
            "[logger]\n"
            "level=note\n"
            "sinks=eventlog,filelog\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kNote),
        // Level system to eventlog,filelog (TS_FR1_04)
        LoggingConfigOkParams(
            "1",  // testname
            "[logger]\n"
            "level=system\n"
            "sinks=eventlog,filelog\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kSystem),
        // All sinks with note and system included (TS_FR1_05)
        LoggingConfigOkParams(
            "2",  // testname
            "[logger]\n"
            "level=debug\n"
            "sinks=eventlog,filelog,consolelog\n"
            "[consolelog]\n"
            "level=note\n"
            "[eventlog]\n"
            "level=system\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNote,
            /* filelog_expected_level =  */ LogLevel::kDebug),
        // Verify filename option is disregarded by eventlog sink
        LoggingConfigOkParams(
            "3",  // testname
            "[logger]\n"
            "level=system\n"
            "sinks=eventlog,filelog\n"
            "[eventlog]\n"
            "filename=foo.log",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kSystem)),
    [](auto const &info) { return info.param.test_name; });
#endif

/**************************************************/
/* Tests for logger configuration errors          */
/**************************************************/

struct LoggingConfigErrorParams {
  std::string logger_config;
  bool logging_folder_empty;

  std::string expected_error;

  LoggingConfigErrorParams(const std::string &logger_config_,
                           const bool logging_folder_empty_,
                           const std::string &expected_error_)
      : logger_config(logger_config_),
        logging_folder_empty(logging_folder_empty_),
        expected_error(expected_error_) {}
};

::std::ostream &operator<<(::std::ostream &os,
                           const LoggingConfigErrorParams &ltp) {
  return os << "config=" << ltp.logger_config
            << ", logging_folder_empty=" << ltp.logging_folder_empty;
}

class RouterLoggingConfigError
    : public RouterLoggingTest,
      public ::testing::WithParamInterface<LoggingConfigErrorParams> {};

/** @test This test verifies that a proper error gets printed on the console for
 * a particular logging configuration
 */
TEST_P(RouterLoggingConfigError, check) {
  auto test_params = GetParam();

  TempDirectory tmp_dir;
  auto conf_params = get_DEFAULT_defaults();
  conf_params["logging_folder"] =
      test_params.logging_folder_empty ? "" : tmp_dir.name();

  TempDirectory conf_dir("conf");
  const std::string conf_text =
      "[routertestplugin_logger]\n" + test_params.logger_config;

  const std::string conf_file =
      create_config_file(conf_dir.name(), conf_text, &conf_params);

  auto &router = launch_router_for_fail({"-c", conf_file});
  check_exit_code(router, EXIT_FAILURE);

  // the error happens during the logger initialization so we expect the message
  // on the console which is the default sink until we switch to the
  // configuration from the config file
  const std::string console_log_txt = router.get_full_output();

  EXPECT_THAT(console_log_txt, HasSubstr(test_params.expected_error))
      << "\nconsole:\n"
      << console_log_txt;
}

INSTANTIATE_TEST_SUITE_P(
    Spec, RouterLoggingConfigError,
    ::testing::Values(
        // Unknown sink name in the [logger] section
        /*0*/ LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=unknown\n"
            "level=debug\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "Configuration error: Unsupported logger sink type: 'unknown'"),

        // Empty sinks option
        /*1*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "  init 'logger' failed: sinks option does not contain any "
            "valid sink name, was ''"),

        // Empty sinks list
        /*2*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=,\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "  init 'logger' failed: Unsupported logger sink type: ''"),

        // Leading comma on a sinks list
        /*3*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=,consolelog\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "  init 'logger' failed: Unsupported logger sink type: ''"),

        // Terminating comma on a sinks list
        /*4*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=consolelog,\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "  init 'logger' failed: Unsupported logger sink type: ''"),

        // Two commas separating sinks
        /*5*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=consolelog,,filelog\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "  init 'logger' failed: Unsupported logger sink type: ''"),

        // Empty space as a sink name
        /*6*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks= \n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "  init 'logger' failed: sinks option does not contain any "
            "valid sink name, was ''"),

        // Invalid log level in the [logger] section
        /*7*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=consolelog\n"
            "level=invalid\n"
            "[consolelog]\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "Configuration error: Log level 'invalid' is not valid. Valid "
            "values are: fatal, system, error, warning, info, note, and debug"),

        // Invalid log level in the sink section
        /*8*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=consolelog\n"
            "[consolelog]\n"
            "level=invalid\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "Configuration error: Log level 'invalid' is not valid. Valid "
            "values are: fatal, system, error, warning, info, note, and debug"),

        // Both level and sinks values invalid in the [logger] section
        /*9*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=invalid\n"
            "level=invalid\n"
            "[consolelog]\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "Configuration error: Log level 'invalid' is not valid. Valid "
            "values are: fatal, system, error, warning, info, note, and debug"),

        // Logging folder is empty but we request filelog as sink
        /*10*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=filelog\n",
            /* logging_folder_empty = */ true,
            /* expected_error =  */
            "  init 'logger' failed: filelog sink configured but the "
            "logging_folder is empty")));

#ifndef _WIN32
INSTANTIATE_TEST_SUITE_P(
    LoggingConfigErrorUnix, RouterLoggingConfigError,
    ::testing::Values(
        // We can't reliably check if the syslog logging is working with a
        // component test as this is too operating system intrusive and we are
        // supposed to run on pb2 environment. Let's at least check that this
        // sink type is supported
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=syslog\n"
            "[syslog]\n"
            "level=invalid\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "Configuration error: Log level 'invalid' is not valid. Valid "
            "values are: fatal, system, error, warning, info, note, and debug"),

        // Let's also check that the eventlog is NOT supported
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=eventlog\n"
            "[eventlog]\n"
            "level=invalid\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "Loading plugin for config-section '[eventlog]' failed")));
#else
INSTANTIATE_TEST_SUITE_P(
    LoggingConfigErrorWindows, RouterLoggingConfigError,
    ::testing::Values(
        // We can't reliably check if the eventlog logging is working with a
        // component test as this is too operating system intrusive and also
        // requires admin privileges to setup and we are supposed to run on pb2
        // environment. Let's at least check that this sink type is supported
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=eventlog\n"
            "[eventlog]\n"
            "level=invalid\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "Configuration error: Log level 'invalid' is not valid. Valid "
            "values are: fatal, system, error, warning, info, note, and debug"),

        // Let's also check that the syslog is NOT supported
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=syslog\n"
            "[syslog]\n"
            "level=invalid\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "Loading plugin for config-section '[syslog]' failed")));
#endif

class RouterLoggingTestTimestampPrecisionConfig
    : public RouterLoggingTest,
      public ::testing::WithParamInterface<LoggingConfigOkParams> {};

static std::string ts_regex(LogTimestampPrecision precision) {
  const std::string base_regex(
#ifdef GTEST_USES_SIMPLE_RE
      "\\d\\d\\d\\d-\\d\\d-\\d\\d "
      "\\d\\d:\\d\\d:\\d\\d"
#else
      "[0-9]{4}-[0-9]{2}-[0-9]{2} "
      "[0-9]{2}:[0-9]{2}:[0-9]{2}"
#endif
  );

  switch (precision) {
    case LogTimestampPrecision::kNotSet:
    case LogTimestampPrecision::kSec:
      // EXPECT 12:00:00
      return base_regex + " ";
    case LogTimestampPrecision::kMilliSec:
      // EXPECT 12:00:00.000
      return base_regex +
#ifdef GTEST_USES_SIMPLE_RE
             "\\.\\d\\d\\d "
#else
             "\\.[0-9]{3} ";
#endif
          ;
    case LogTimestampPrecision::kMicroSec:
      // EXPECT 12:00:00.000000
      return base_regex +
#ifdef GTEST_USES_SIMPLE_RE
             "\\.\\d\\d\\d\\d\\d\\d "
#else
             "\\.[0-9]{6} "
#endif
          ;
    case LogTimestampPrecision::kNanoSec:
      // EXPECT 12:00:00.000000000
      return base_regex +
#ifdef GTEST_USES_SIMPLE_RE
             "\\.\\d\\d\\d\\d\\d\\d\\d\\d\\d "
#else
             "\\.[0-9]{9} "
#endif
          ;
  }

  return {};
}

/** @test This test verifies that a proper loggs are written to selected sinks
 * for various sinks/levels combinations.
 */
TEST_P(RouterLoggingTestTimestampPrecisionConfig, check) {
  auto test_params = GetParam();

  TempDirectory tmp_dir;

  // Different log entries that are expected for different levels, but we only
  // care that something is logged, not what, when checking timestamps.

  const std::string kOtherPluginConfig = "[routertestplugin_logger]\n";

  auto conf_params = get_DEFAULT_defaults();
  conf_params["logging_folder"] =
      test_params.logging_folder_empty ? "" : tmp_dir.name();

  TempDirectory conf_dir("conf");
  const std::string conf_text =
      test_params.logger_config + "\n" + kOtherPluginConfig;

  const std::string conf_file =
      create_config_file(conf_dir.name(), conf_text, &conf_params);

  auto &router = ProcessManager::launch_router({"-c", conf_file});
  router.send_clean_shutdown_event();
  EXPECT_NO_THROW(router.wait_for_exit());

  // check the console log if it contains what's expected
  std::string console_log_txt = router.get_full_output();

  // strip first line before checking if needed
  const std::string prefix = "logging facility initialized";
  if (std::mismatch(console_log_txt.begin(), console_log_txt.end(),
                    prefix.begin(), prefix.end())
          .second == prefix.end()) {
    console_log_txt.erase(0, console_log_txt.find("\n") + 1);
  }

  if (test_params.consolelog_expected_level != LogLevel::kNotSet) {
    std::vector<std::string> lines;
    std::istringstream ss(console_log_txt);
    for (std::string line; std::getline(ss, line);) {
      lines.push_back(line);
    }

    auto regex = ts_regex(test_params.consolelog_expected_timestamp_precision);
    ASSERT_FALSE(regex.empty());

    EXPECT_THAT(lines, ::testing::Contains(::testing::ContainsRegex(regex)));
  }

  // check the file log if it contains what's expected
  std::string file_log_txt =
      router.get_logfile_content("mysqlrouter.log", tmp_dir.name());

  // strip first line before checking if needed
  if (std::mismatch(file_log_txt.begin(), file_log_txt.end(), prefix.begin(),
                    prefix.end())
          .second == prefix.end()) {
    file_log_txt.erase(0, file_log_txt.find("\n") + 1);
  }

  if (test_params.filelog_expected_level != LogLevel::kNotSet) {
    std::vector<std::string> lines;
    std::istringstream ss(file_log_txt);
    for (std::string line; std::getline(ss, line);) {
      lines.push_back(line);
    }

    auto regex = ts_regex(test_params.filelog_expected_timestamp_precision);
    ASSERT_FALSE(regex.empty());

    EXPECT_THAT(lines, ::testing::Contains(::testing::ContainsRegex(regex)));
  }
}

#define TS_FR1_1_STR(x)        \
  "[logger]\n"                 \
  "level=debug\n"              \
  "sinks=consolelog,filelog\n" \
  "timestamp_precision=" x     \
  "\n"                         \
  "[consolelog]\n\n[filelog]\n\n"

#define TS_FR1_2_STR(x) TS_FR1_1_STR(x)

#define TS_FR1_3_STR(x) TS_FR1_1_STR(x)

INSTANTIATE_TEST_SUITE_P(
    Spec, RouterLoggingTestTimestampPrecisionConfig,
    ::testing::Values(
        // no logger section, no sinks sections
        // logging_folder not empty so we are expected to log to the file
        // with a warning level so info and debug logs will not be there
        LoggingConfigOkParams(
            "0",  // testname
            "",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kWarning,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNotSet,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNotSet),
        // Two sinks, common timestamp_precision
        /*** TS_FR1_1 ***/
        /*TS_FR1_1.1*/
        LoggingConfigOkParams(
            "1",  // testname
            TS_FR1_1_STR("second"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec),
        /*TS_FR1_1.2*/
        LoggingConfigOkParams(
            "2",  // testname
            TS_FR1_1_STR("Second"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec),
        /*TS_FR1_1.3*/
        LoggingConfigOkParams(
            "3",  // testname
            TS_FR1_1_STR("sec"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec),
        /*TS_FR1_1.4*/
        LoggingConfigOkParams(
            "4",  // testname
            TS_FR1_1_STR("SEC"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec),
        /*TS_FR1_1.5*/
        LoggingConfigOkParams(
            "5",  // testname
            TS_FR1_1_STR("s"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec),
        /*TS_FR1_1.6*/
        LoggingConfigOkParams(
            "6",  // testname
            TS_FR1_1_STR("S"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec),
        /*** TS_FR1_2 ***/
        /*TS_FR1_2.1*/
        LoggingConfigOkParams(
            "7",  // testname
            TS_FR1_2_STR("millisecond"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec),
        /*TS_FR1_2.2*/
        LoggingConfigOkParams(
            "8",  // testname
            TS_FR1_2_STR("MILLISECOND"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec),
        /*TS_FR1_2.3*/
        LoggingConfigOkParams(
            "9",  // testname
            TS_FR1_2_STR("msec"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec),
        /*TS_FR1_2.4*/
        LoggingConfigOkParams(
            "10",  // testname
            TS_FR1_2_STR("MSEC"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec),
        /*TS_FR1_2.5*/
        LoggingConfigOkParams(
            "11",  // testname
            TS_FR1_2_STR("ms"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec),
        /*TS_FR1_2.6*/
        LoggingConfigOkParams(
            "12",  // testname
            TS_FR1_2_STR("MS"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec),
        /*** TS_FR1_3 ***/
        /*TS_FR1_3.1*/
        LoggingConfigOkParams(
            "13",  // testname
            TS_FR1_3_STR("microsecond"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec),
        /*TS_FR1_3.2*/
        LoggingConfigOkParams(
            "14",  // testname
            TS_FR1_3_STR("Microsecond"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec),
        /*TS_FR1_3.3*/
        LoggingConfigOkParams(
            "15",  // testname
            TS_FR1_3_STR("usec"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec),
        /*TS_FR1_3.4*/
        LoggingConfigOkParams(
            "16",  // testname
            TS_FR1_3_STR("UsEC"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec),
        /*TS_FR1_3.5*/
        LoggingConfigOkParams(
            "17",  // testname
            TS_FR1_3_STR("us"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec),
        /*TS_FR1_3.5*/
        LoggingConfigOkParams(
            "18",  // testname
            TS_FR1_3_STR("US"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMicroSec),
        /*** TS_FR1_4 ***/
        /*TS_FR1_4.1*/
        LoggingConfigOkParams(
            "19",  // testname
            TS_FR1_3_STR("nanosecond"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec),
        /*TS_FR1_4.2*/
        LoggingConfigOkParams(
            "20",  // testname
            TS_FR1_3_STR("NANOSECOND"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec),
        /*TS_FR1_4.3*/
        LoggingConfigOkParams(
            "21",  // testname
            TS_FR1_3_STR("nsec"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec),
        /*TS_FR1_4.4*/
        LoggingConfigOkParams(
            "22",  // testname
            TS_FR1_3_STR("nSEC"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec),
        /*TS_FR1_4.5*/
        LoggingConfigOkParams(
            "23",  // testname
            TS_FR1_3_STR("ns"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec),
        /*TS_FR1_4.6*/
        LoggingConfigOkParams(
            "24",  // testname
            TS_FR1_3_STR("NS"),
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec),
        /*TS_FR4_2*/
        LoggingConfigOkParams(
            "25",  // testname
            "[logger]\n"
            "level=debug\n"
            "sinks=filelog\n"
            "[filelog]\n"
            "timestamp_precision=ms\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kNotSet,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNotSet,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kMilliSec),
        /*TS_FR4_3*/
        LoggingConfigOkParams(
            "26",  // testname
            "[logger]\n"
            "level=debug\n"
            "sinks=filelog,consolelog\n"
            "[consolelog]\n"
            "timestamp_precision=ns\n",
            /* logging_folder_empty = */ false,
            /* consolelog_expected_level =  */ LogLevel::kDebug,
            /* filelog_expected_level =  */ LogLevel::kDebug,
            /* consolelog_expected_timestamp_precision = */
            LogTimestampPrecision::kNanoSec,
            /* filelog_expected_timestamp_precision = */
            LogTimestampPrecision::kSec)),
    [](auto const &info) { return info.param.test_name; });

INSTANTIATE_TEST_SUITE_P(
    Failures, RouterLoggingConfigError,
    ::testing::Values(
        // Unknown timestamp_precision value in a sink
        /*0*/ /*TS_FR3_1*/ LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=consolelog\n"
            "[consolelog]\n"
            "timestamp_precision=unknown\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "Configuration error: Timestamp precision 'unknown' is not valid. "
            "Valid values are: second, sec, s, millisecond, msec, ms, "
            "microsecond, usec, us, nanosecond, nsec, and ns"),
        // Unknown timestamp_precision value in the [logger] section
        /*1*/ /*TS_FR3_1*/
        LoggingConfigErrorParams(
            "[logger]\n"
            "sinks=consolelog,filelog\n"
            "timestamp_precision=unknown\n",
            /* logging_folder_empty = */ false,
            /* expected_error =  */
            "Configuration error: Timestamp precision 'unknown' is not valid. "
            "Valid values are: second, sec, s, millisecond, msec, ms, "
            "microsecond, usec, us, nanosecond, nsec, and ns"),
        /*2*/ /*TS_FR4_1*/
        LoggingConfigErrorParams("[logger]\n"
                                 "sinks=consolelog,filelog\n"
                                 "timestamp_precision=ms\n"
                                 "timestamp_precision=ns\n",
                                 /* logging_folder_empty = */ false,
                                 /* expected_error =  */
                                 "Configuration error: Option "
                                 "'timestamp_precision' already defined.")));
#ifndef _WIN32
INSTANTIATE_TEST_SUITE_P(
    LoggingConfigTimestampPrecisionErrorUnix, RouterLoggingConfigError,
    ::testing::Values(
        /*0*/ /* TS_HLD_1 */
        LoggingConfigErrorParams("[logger]\n"
                                 "sinks=syslog\n"
                                 "[syslog]\n"
                                 "timestamp_precision=ms\n",
                                 /* logging_folder_empty = */ false,
                                 /* expected_error =  */
                                 "Configuration error: timestamp_precision not "
                                 "valid for 'syslog'")));
#else
INSTANTIATE_TEST_SUITE_P(
    LoggingConfigTimestampPrecisionErrorWindows, RouterLoggingConfigError,
    ::testing::Values(
        /*0*/ /* TS_HLD_3 */
        LoggingConfigErrorParams("[logger]\n"
                                 "sinks=eventlog\n"
                                 "[eventlog]\n"
                                 "timestamp_precision=ms\n",
                                 /* logging_folder_empty = */ false,
                                 /* expected_error =  */
                                 "Configuration error: timestamp_precision not "
                                 "valid for 'eventlog'")));
#endif

TEST_F(RouterLoggingTest, very_long_router_name_gets_properly_logged) {
  // This test verifies that a very long router name gets truncated in the
  // logged message (this is done because if it doesn't happen, the entire
  // message will exceed log message max length, and then the ENTIRE message
  // will get truncated instead. It's better to truncate the long name rather
  // than the stuff that follows it).
  // Router should report the error on STDERR and exit

  const std::string json_stmts = get_data_dir().join("bootstrap_gr.js").str();
  TempDirectory bootstrap_dir;

  const auto server_port = port_pool_.get_next_available();

  // launch mock server and wait for it to start accepting connections
  auto &server_mock = launch_mysql_server_mock(json_stmts, server_port);
  ASSERT_NO_FATAL_FAILURE(check_port_ready(server_mock, server_port));

  constexpr char name[] =
      "veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryvery"
      "veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryvery"
      "veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryvery"
      "veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryvery"
      "verylongname";
  static_assert(
      sizeof(name) > 255,
      "too long");  // log message max length is 256, we want something that
                    // guarantees the limit would be exceeded

  // launch the router in bootstrap mode
  auto &router = launch_router_for_fail({
      "--bootstrap=127.0.0.1:" + std::to_string(server_port),
      "--name",
      name,
      "-d",
      bootstrap_dir.name(),
  });

  // wait for router to exit
  check_exit_code(router, EXIT_FAILURE);

  // expect something like this to appear on STDERR
  // Error: Router name
  // 'veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryv...'
  // too long (max 255).
  const std::string out = router.get_full_output();
  EXPECT_THAT(out.c_str(),
              HasSubstr("Error: Router name "
                        "'veryveryveryveryveryveryveryveryveryveryveryveryveryv"
                        "eryveryveryveryveryveryv...' too long (max 255)."));
}

/**
 * @test verify that debug logs are not written to console during bootstrap if
 * bootstrap configuration file is not provided.
 */
TEST_F(RouterLoggingTest, is_debug_logs_disabled_if_no_bootstrap_config_file) {
  const std::string json_stmts = get_data_dir().join("bootstrap_gr.js").str();

  TempDirectory bootstrap_dir;

  const auto server_port = port_pool_.get_next_available();

  // launch mock server and wait for it to start accepting connections
  /*auto &server_mock =*/launch_mysql_server_mock(json_stmts, server_port,
                                                  false);
  // ASSERT_NO_FATAL_FAILURE(check_port_ready(server_mock, server_port));

  // launch the router in bootstrap mode
  auto &router = launch_router_for_bootstrap(
      {
          "--bootstrap=127.0.0.1:" + std::to_string(server_port),
          "-d",
          bootstrap_dir.name(),
      },
      EXIT_SUCCESS);

  // check if the bootstrapping was successful
  check_exit_code(router, EXIT_SUCCESS);
  EXPECT_THAT(router.get_full_output(),
              testing::Not(testing::HasSubstr("SELECT ")));
}

/**
 * @test verify that debug logs are written to console during bootstrap if
 * log_level is set to DEBUG in bootstrap configuration file.
 */
TEST_F(RouterLoggingTest, is_debug_logs_enabled_if_bootstrap_config_file) {
  const std::string json_stmts = get_data_dir().join("bootstrap_gr.js").str();

  TempDirectory bootstrap_dir;
  TempDirectory bootstrap_conf;

  const auto server_port = port_pool_.get_next_available();

  // launch mock server and wait for it to start accepting connections
  auto &server_mock = launch_mysql_server_mock(json_stmts, server_port, false);
  ASSERT_NO_FATAL_FAILURE(check_port_ready(server_mock, server_port));

  // launch the router in bootstrap mode
  std::string logger_section = "[logger]\nlevel = DEBUG\n";
  auto conf_params = get_DEFAULT_defaults();
  // we want to log to the console
  conf_params["logging_folder"] = "";
  std::string conf_file = ProcessManager::create_config_file(
      bootstrap_conf.name(), logger_section, &conf_params, "bootstrap.conf", "",
      false);

  auto &router = launch_router_for_bootstrap(
      {
          "--bootstrap=127.0.0.1:" + std::to_string(server_port),
          "--force",
          "-d",
          bootstrap_dir.name(),
          "-c",
          conf_file,
      },
      EXIT_SUCCESS);

  // check if the bootstrapping was successful
  check_exit_code(router, EXIT_SUCCESS);

  // check if log output contains the SQL queries.
  //
  // SQL queries are logged with host:port at the start.
  EXPECT_THAT(router.get_full_output(),
              testing::HasSubstr("127.0.0.1:" + std::to_string(server_port)));
}

/**
 * @test verify that debug logs are written to mysqlrouter.log file during
 * bootstrap if loggin_folder is provided in bootstrap configuration file
 */
TEST_F(RouterLoggingTest, is_debug_logs_written_to_file_if_logging_folder) {
  const std::string json_stmts = get_data_dir().join("bootstrap_gr.js").str();

  TempDirectory bootstrap_dir;
  TempDirectory bootstrap_conf;

  const auto server_port = port_pool_.get_next_available();

  // launch mock server and wait for it to start accepting connections
  auto &server_mock = launch_mysql_server_mock(json_stmts, server_port, false);
  ASSERT_NO_FATAL_FAILURE(check_port_ready(server_mock, server_port));

  // create config with logging_folder set to that directory
  std::map<std::string, std::string> params = {{"logging_folder", ""}};
  params.at("logging_folder") = bootstrap_conf.name();
  TempDirectory conf_dir("conf");
  const std::string conf_file =
      create_config_file(conf_dir.name(), "[logger]\nlevel = DEBUG\n", &params);

  auto &router = launch_router_for_bootstrap(
      {
          "--bootstrap=127.0.0.1:" + std::to_string(server_port),
          "--force",
          "-d",
          bootstrap_dir.name(),
          "-c",
          conf_file,
      },
      EXIT_SUCCESS);

  // check if the bootstrapping was successful
  check_exit_code(router, EXIT_SUCCESS);

  // check if log output contains the SQL queries.
  //
  // SQL queries are logged with host:port at the start.
  auto file_content =
      router.get_logfile_content("mysqlrouter.log", bootstrap_conf.name());
  auto lines = mysql_harness::split_string(file_content, '\n');

  EXPECT_THAT(lines, ::testing::Contains(::testing::HasSubstr(
                         "127.0.0.1:" + std::to_string(server_port))));
}

/**
 * @test verify that normal output is written to stdout during bootstrap if
 * logging_folder is not provided in bootstrap configuration file.
 *
 * @test verify that logs are not written to stdout during bootstrap.
 */
TEST_F(RouterLoggingTest, bootstrap_normal_logs_written_to_stdout) {
  const std::string json_stmts = get_data_dir().join("bootstrap_gr.js").str();

  TempDirectory bootstrap_dir;
  TempDirectory bootstrap_conf;

  const auto server_port = port_pool_.get_next_available();

  // launch mock server and wait for it to start accepting connections
  auto &server_mock = launch_mysql_server_mock(json_stmts, server_port, false);
  ASSERT_NO_FATAL_FAILURE(check_port_ready(server_mock, server_port));

  // launch the router in bootstrap mode
  std::string logger_section = "[logger]\nlevel = DEBUG\n";
  auto conf_params = get_DEFAULT_defaults();
  // we want to log to the console
  conf_params["logging_folder"] = "";
  std::string conf_file = ProcessManager::create_config_file(
      bootstrap_conf.name(), logger_section, &conf_params, "bootstrap.conf", "",
      false);

  auto &router = launch_router_for_bootstrap(
      {
          "--bootstrap=127.0.0.1:" + std::to_string(server_port),
          "--force",
          "-d",
          bootstrap_dir.name(),
          "-c",
          conf_file,
      },
      EXIT_SUCCESS, true, true, /*catch_sterr=*/false);

  // check if the bootstrapping was successful
  check_exit_code(router, EXIT_SUCCESS);

  // check if logs are not written to output
  EXPECT_THAT(router.get_full_output(),
              testing::Not(testing::HasSubstr("SELECT ")));

  // check if normal output is written to output
  EXPECT_THAT(router.get_full_output(),
              testing::HasSubstr("After this MySQL Router has been started "
                                 "with the generated configuration"));

  EXPECT_THAT(router.get_full_output(),
              testing::HasSubstr("MySQL Classic protocol"));

  EXPECT_THAT(router.get_full_output(), testing::HasSubstr("MySQL X protocol"));
}

class MetadataCacheLoggingTest : public RouterLoggingTest {
 protected:
  void SetUp() override {
    RouterLoggingTest::SetUp();

    mysql_harness::DIM &dim = mysql_harness::DIM::instance();
    // RandomGenerator
    dim.set_RandomGenerator(
        []() {
          static mysql_harness::RandomGenerator rg;
          return &rg;
        },
        [](mysql_harness::RandomGeneratorInterface *) {});

    cluster_nodes_ports = {port_pool_.get_next_available(),
                           port_pool_.get_next_available(),
                           port_pool_.get_next_available()};
    cluster_nodes_http_ports = {port_pool_.get_next_available(),
                                port_pool_.get_next_available(),
                                port_pool_.get_next_available()};
    router_port_ = port_pool_.get_next_available();
    metadata_cache_section = get_metadata_cache_section(cluster_nodes_ports);
    routing_section =
        get_metadata_cache_routing_section("PRIMARY", "round-robin", "");
  }

  std::string get_static_routing_section() {
    return mysql_harness::ConfigBuilder::build_section(
        "routing:test_default", {
                                    {"bind_port", std::to_string(router_port_)},
                                    {"destinations", "127.0.0.1"},
                                    {"routing_strategy", "first-available"},
                                });
  }

  std::string get_metadata_cache_section(std::vector<uint16_t> ports) {
    std::string metadata_caches;

    for (const auto &port : ports) {
      if (!metadata_caches.empty()) {
        metadata_caches.append(",");
      }
      metadata_caches += "mysql://127.0.0.1:" + std::to_string(port);
    }

    return mysql_harness::ConfigBuilder::build_section(
        "metadata_cache:test",
        {
            {"router_id", "1"},
            {"bootstrap_server_addresses", metadata_caches},
            {"user", "mysql_router1_user"},
            {"metadata_cluster", "test"},
            {"connect_timeout", "1"},
            {"ttl", std::to_string(static_cast<double>(ttl_.count()) / 1000)},
        });
  }

  std::string get_metadata_cache_routing_section(const std::string &role,
                                                 const std::string &strategy,
                                                 const std::string &mode = "") {
    std::vector<std::pair<std::string, std::string>> options{
        {"bind_port", std::to_string(router_port_)},
        {"destinations", "metadata-cache://test/default?role=" + role},
        {"protocol", "classic"},
    };

    if (!strategy.empty()) options.emplace_back("routing_strategy", strategy);
    if (!mode.empty()) options.emplace_back("mode", mode);

    return mysql_harness::ConfigBuilder::build_section("routing:test_default",
                                                       options);
  }

  std::string init_keyring_and_config_file(const std::string &conf_dir,
                                           bool log_to_console) {
    return init_keyring_and_config_file(
        conf_dir, metadata_cache_section + "\n" + routing_section,
        log_to_console);
  }

  std::string init_keyring_and_config_file(const std::string &conf_dir) {
    return init_keyring_and_config_file(conf_dir, false);
  }

  std::string init_keyring_and_config_file(const std::string &conf_dir,
                                           const std::string &config) {
    return init_keyring_and_config_file(conf_dir, config, false);
  }

  std::string init_keyring_and_config_file(const std::string &conf_dir,
                                           const std::string &config,
                                           bool log_to_console) {
    auto default_section = get_DEFAULT_defaults();
    init_keyring(default_section, temp_test_dir.name());
    default_section["logging_folder"] =
        log_to_console ? "" : get_logging_dir().str();
    const std::string sinks =
        (log_to_console ? "consolelog,"s : "") + "filelog";
    return create_config_file(conf_dir,
                              mysql_harness::ConfigBuilder::build_section(
                                  "logger",
                                  {
                                      {"level", "DEBUG"},
                                      {"timestamp_precision", "millisecond"},
                                      {"sinks", sinks},
                                  }) +
                                  "\n" + config,
                              &default_section);
  }

  TempDirectory temp_test_dir;
  std::vector<uint16_t> cluster_nodes_ports;
  std::vector<uint16_t> cluster_nodes_http_ports;
  uint16_t router_port_;
  std::string metadata_cache_section;
  std::string routing_section;
  const std::chrono::milliseconds ttl_{200};
};

template <class F>
bool retry_for(F &&f, std::chrono::milliseconds duration) {
  using clock_type = std::chrono::steady_clock;

  auto sleep_time = duration / 20;
  auto end_time = clock_type::now() + duration;

  do {
    auto res = f();

    if (res) return true;

    RouterComponentTest::sleep_for(sleep_time);
  } while (clock_type::now() < end_time);

  return false;
}

/**
 * @test verify if error message is logged if router cannot connect to any
 *       metadata server.
 */
TEST_F(MetadataCacheLoggingTest,
       log_error_when_cannot_connect_to_any_metadata_server) {
  TempDirectory conf_dir;

  // launch the router with metadata-cache configuration
  auto &router =
      launch_router({"-c", init_keyring_and_config_file(conf_dir.name())},
                    EXIT_SUCCESS,  // expected-exit-code
                    false,         // catch-stderr
                    false,         // with-sudo
                    -1s            // wait-ready
      );

  // expect something like this to appear on STDERR
  // 2017-12-21 17:22:35 metadata_cache ERROR [7ff0bb001700] Failed connecting
  // with any of the 3 metadata servers
  const auto fail_msg =
      "Failed fetching metadata from any of the 3 metadata servers.";

  // Log as error only once
  const auto error_timestamp = get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache ERROR.*"} + fail_msg, 1, 20 * ttl_);
  EXPECT_TRUE(error_timestamp);
  EXPECT_FALSE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache ERROR.*"} + fail_msg, 2, 20 * ttl_));
  // After logging an error next logs should be debug (unless the server state
  // changes)
  const auto debug_timestamp = get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache DEBUG.*"} + fail_msg, 1, 20 * ttl_);
  EXPECT_TRUE(debug_timestamp);
  EXPECT_GT(debug_timestamp.value(), error_timestamp.value());

  // Launch metadata server
  const auto http_port = cluster_nodes_http_ports[0];
  auto &server = launch_mysql_server_mock(
      get_data_dir().join("metadata_dynamic_nodes.js").str(),
      cluster_nodes_ports[0], EXIT_SUCCESS, false, http_port);
  ASSERT_NO_FATAL_FAILURE(check_port_ready(server, cluster_nodes_ports[0]));
  EXPECT_TRUE(MockServerRestClient(http_port).wait_for_rest_endpoint_ready());
  set_mock_metadata(http_port, "",
                    classic_ports_to_gr_nodes(cluster_nodes_ports), 0,
                    classic_ports_to_cluster_nodes(cluster_nodes_ports));
  wait_for_transaction_count_increase(http_port);

  // We report to log info that we have connected only if there was an error,
  // otherwise those reports should be treated as debug
  const auto connect_msg = "Connected with metadata server";
  EXPECT_TRUE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache INFO.*"} + connect_msg, 1, 20 * ttl_));
  EXPECT_FALSE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache INFO.*"} + connect_msg, 3, 5 * ttl_));
  EXPECT_TRUE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache DEBUG.*"} + connect_msg, 1, 20 * ttl_));

  server.send_clean_shutdown_event();
  server.wait_for_exit();
  std::this_thread::sleep_for(ttl_);
  // Log error after server was shut down
  EXPECT_TRUE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache ERROR.*"} + fail_msg, 2, 80 * ttl_));
}

/**
 * @test verify if appropriate warning messages are logged when cannot connect
 * to first metadata server, but can connect to another one.
 */
TEST_F(MetadataCacheLoggingTest,
       log_warning_when_cannot_connect_to_first_metadata_server) {
  TempDirectory conf_dir("conf");

  // launch second metadata server
  const auto http_port = cluster_nodes_http_ports[1];
  auto &server = launch_mysql_server_mock(
      get_data_dir().join("metadata_3_nodes_first_not_accessible.js").str(),
      cluster_nodes_ports[1], EXIT_SUCCESS, false, http_port);
  ASSERT_NO_FATAL_FAILURE(check_port_ready(server, cluster_nodes_ports[1]));
  EXPECT_TRUE(MockServerRestClient(http_port).wait_for_rest_endpoint_ready());
  set_mock_metadata(http_port, "",
                    classic_ports_to_gr_nodes(cluster_nodes_ports), 1,
                    classic_ports_to_cluster_nodes(cluster_nodes_ports));

  // launch the router with metadata-cache configuration
  auto &router = ProcessManager::launch_router(
      {"-c", init_keyring_and_config_file(conf_dir.name())}, EXIT_SUCCESS, true,
      false, -1s);

  // expect something like this to appear on STDERR:
  //
  // - ... metadata_cache WARNING ... Failed connecting with Metadata Server
  //   127.0.0.1:7002: Can't connect to MySQL server on '127.0.0.1' (111) (2003)
  // - ... metadata_cache WARNING ... While updating metadata, could ...
  const auto connection_failed_msg =
      "Failed connecting with Metadata Server 127\\.0\\.0\\.1:" +
      std::to_string(cluster_nodes_ports[0]);
  const auto update_failed_msg =
      "While updating metadata, could not establish a connection to cluster "
      "'test' through .*" +
      std::to_string(cluster_nodes_ports[0]);

  EXPECT_TRUE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache WARNING.*"} + update_failed_msg, 1,
      20 * ttl_));
  EXPECT_TRUE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache WARNING.*"} + connection_failed_msg, 1,
      20 * ttl_));
  EXPECT_FALSE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache WARNING.*"} + connection_failed_msg, 2,
      5 * ttl_));
  EXPECT_TRUE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache DEBUG.*"} + connection_failed_msg, 1,
      20 * ttl_));

  server.send_clean_shutdown_event();
  server.wait_for_exit();

  auto &new_server = launch_mysql_server_mock(
      get_data_dir().join("metadata_dynamic_nodes.js").str(),
      cluster_nodes_ports[0], EXIT_SUCCESS, false, cluster_nodes_http_ports[0]);
  ASSERT_NO_FATAL_FAILURE(check_port_ready(new_server, cluster_nodes_ports[0]));
  EXPECT_TRUE(MockServerRestClient(cluster_nodes_http_ports[0])
                  .wait_for_rest_endpoint_ready());
  set_mock_metadata(cluster_nodes_http_ports[0], "",
                    classic_ports_to_gr_nodes(cluster_nodes_ports), 0,
                    classic_ports_to_cluster_nodes(cluster_nodes_ports));
  wait_for_transaction_count_increase(cluster_nodes_http_ports[0]);

  const auto connect_msg = "Connected with metadata server running on .*" +
                           std::to_string(cluster_nodes_ports[0]);
  EXPECT_TRUE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache INFO.*"} + connect_msg, 1, 20 * ttl_));
  EXPECT_TRUE(get_log_timestamp(
      router.get_logfile_path(),
      std::string{".*metadata_cache DEBUG.*"} + connect_msg, 1, 20 * ttl_));
}

#ifndef _WIN32

/**
 * @test Checks that the logs rotation works (meaning Router will recreate
 * its log file when it was moved and HUP signal was sent to the Router).
 */
TEST_F(MetadataCacheLoggingTest, log_rotation_by_HUP_signal) {
  TempDirectory conf_dir;

  // launch the router with metadata-cache configuration
  auto &router =
      launch_router({"-c", init_keyring_and_config_file(
                               conf_dir.name(), get_static_routing_section())},
                    EXIT_SUCCESS);

  auto logging_dir = get_logging_dir();
  auto log_file = Path(logging_dir).join("mysqlrouter.log");

  EXPECT_TRUE(retry_for([&log_file]() { return log_file.exists(); }, 1000ms));

  // now let's simulate what logrotate script does
  // move the log_file appending '.1' to its name
  auto log_file_1 = Path(logging_dir).join("mysqlrouter.log.1");

  mysqlrouter::rename_file(log_file.str(), log_file_1.str());
  ::kill(router.get_pid(), SIGHUP);

  // let's wait until something new gets logged (metadata cache TTL has
  // expired), to be sure the default file that we moved is back.
  // Now both old and new files should exist
  EXPECT_TRUE(retry_for([&log_file]() { return log_file.exists(); }, 1000ms));

  EXPECT_TRUE(log_file.exists()) << router.get_logfile_content();
  EXPECT_TRUE(log_file_1.exists());
}

/**
 * @test Checks that the Router continues to log to the file when the
 * SIGHUP gets sent to it and no file replacement is done.
 */
TEST_F(MetadataCacheLoggingTest, log_rotation_by_HUP_signal_no_file_move) {
  TempDirectory conf_dir;

  // launch router with metadata-cache configuration to get a changes in the
  // logfile every once and a while
  auto &router =
      router_spawner()
          .wait_for_sync_point(ProcessManager::Spawner::SyncPoint::RUNNING)
          .expected_exit_code(EXIT_SUCCESS)
          .spawn({"-c", init_keyring_and_config_file(conf_dir.name())});

  auto logging_dir = get_logging_dir();
  auto log_file = Path(logging_dir).join("mysqlrouter.log");

  ASSERT_TRUE(retry_for([&log_file]() { return log_file.exists(); }, 1000ms));

  // grab the current log content
  const std::string log_content = router.get_logfile_content();

  // send the log-rotate signal
  ::kill(router.get_pid(), SIGHUP);

  // wait until something new gets logged;
  std::string log_content_2;

  EXPECT_TRUE(retry_for(
      [log_content, &log_content_2, &router]() {
        log_content_2 = router.get_logfile_content();

        return log_content != log_content_2;
      },
      2000ms));

  // The logfile should still exist
  EXPECT_TRUE(log_file.exists());
  // It should still contain what was there before and more (Router should keep
  // logging)
  EXPECT_THAT(log_content_2, StartsWith(log_content));
  EXPECT_STRNE(log_content_2.c_str(), log_content.c_str());
}

/**
 * @test Checks that the log file will be recreated after a router restart.
 */
TEST_F(MetadataCacheLoggingTest, log_rotation_when_router_restarts) {
  TempDirectory conf_dir;

  auto &router =
      launch_router({"-c", init_keyring_and_config_file(
                               conf_dir.name(), get_static_routing_section())},
                    EXIT_SUCCESS);

  auto log_file = get_logging_dir();
  log_file.append("mysqlrouter.log");

  EXPECT_TRUE(retry_for([&log_file]() { return log_file.exists(); }, 500ms));

  // now stop the router
  int res = router.kill();
  EXPECT_EQ(EXIT_SUCCESS, res) << router.get_full_output();

  // move the log_file appending '.1' to its name
  auto log_file_1 = get_logging_dir();
  log_file_1.append("mysqlrouter.log.1");
  mysqlrouter::rename_file(log_file.str(), log_file_1.str());

  // make the new file read-only
  chmod(log_file_1.c_str(), S_IRUSR);

  // start the router again and check that the new log file got created
  launch_router({"-c", init_keyring_and_config_file(
                           conf_dir.name(), get_static_routing_section())},
                EXIT_SUCCESS);

  EXPECT_TRUE(retry_for([&log_file]() { return log_file.exists(); }, 500ms));
}

/**
 * @test Checks that sending SIGHUP when the log file is read only results in a
 * failure.
 */
TEST_F(MetadataCacheLoggingTest, log_rotation_read_only) {
  TempDirectory conf_dir;

  SCOPED_TRACE("// launch the router with static routing configuration");
  auto &router =
      launch_router({"-c", init_keyring_and_config_file(
                               conf_dir.name(), get_static_routing_section())},
                    EXIT_FAILURE);

  auto logging_dir = get_logging_dir();
  auto log_file = Path(logging_dir).join("mysqlrouter.log");

  SCOPED_TRACE("// wait for logfile " + log_file.str() + " to appear");

  EXPECT_TRUE(retry_for([log_file]() { return log_file.exists(); }, 500ms));

  SCOPED_TRACE("// move the log_file appending '.1' to its name");
  auto log_file_1 = Path(logging_dir).join("mysqlrouter.log.1");
  mysqlrouter::rename_file(log_file.str(), log_file_1.str());

  SCOPED_TRACE("// 'manually' recreate the log file and make it read only");
  {
    std::ofstream logf(log_file.str());
    EXPECT_TRUE(logf.good());
  }
  EXPECT_TRUE(retry_for([log_file]() { return log_file.exists(); }, 500ms));
  chmod(log_file.c_str(), S_IRUSR);

  const auto pid = router.get_pid();
  SCOPED_TRACE("// send the log-rotate signal to PID " + std::to_string(pid));
  ::kill(pid, SIGHUP);

  SCOPED_TRACE("// we expect the router to exit");
  // as the logfile is no longer usable it will fallback to logging to the
  // stderr
  check_exit_code(router, EXIT_FAILURE);
  EXPECT_THAT(router.get_full_output(),
              HasSubstr("File exists, but cannot open for writing"));
  EXPECT_THAT(router.get_full_output(), HasSubstr("Unloading all plugins."));
}

/**
 * @test Checks that the logs rotation does not cause any crash in case of
 * not logging to the file (logging_foler empty == logging to the std:cerr)
 */
TEST_F(MetadataCacheLoggingTest, log_rotation_stdout) {
  TempDirectory conf_dir;

  auto default_section = get_DEFAULT_defaults();

  // send log to stderr
  default_section["logging_folder"] = "";

  const auto config = mysql_harness::join(
      std::vector<std::string>{
          mysql_harness::ConfigBuilder::build_section("logger",
                                                      {{"level", "DEBUG"}}),
          mysql_harness::ConfigBuilder::build_section("io", {{"threads", "1"}}),
          get_static_routing_section()},
      "\n");

  auto &router = launch_router(
      {"-c", create_config_file(conf_dir.name(), config, &default_section)},
      EXIT_SUCCESS);

  // send SIGHUP, should have no impact.
  ::kill(router.get_pid(), SIGHUP);

  // wait a bit for the router handle the signal
  RouterComponentTest::sleep_for(200ms);
}

#endif

/**************************************************/
/* Tests for valid logger filename configurations */
/**************************************************/

#define DEFAULT_LOGFILE_NAME "mysqlrouter.log"
#define USER_LOGFILE_NAME "foo.log"
#define USER_LOGFILE_NAME_2 "bar.log"

struct LoggingConfigFilenameOkParams {
  const std::string logger_config;
  const std::string filename;
  const bool console_to_stderr;

  LoggingConfigFilenameOkParams(std::string logger_config_,
                                std::string filename_)
      : logger_config(std::move(logger_config_)),
        filename(std::move(filename_)),
        console_to_stderr(true) {}

  LoggingConfigFilenameOkParams(std::string logger_config_,
                                std::string filename_, bool console_to_stderr_)
      : logger_config(std::move(logger_config_)),
        filename(std::move(filename_)),
        console_to_stderr(console_to_stderr_) {}
};

class RouterLoggingTestConfigFilename
    : public RouterLoggingTest,
      public ::testing::WithParamInterface<LoggingConfigFilenameOkParams> {};

/** @test This test verifies that a proper log filename is written to
 * for various sinks/filename combinations.
 */
TEST_P(RouterLoggingTestConfigFilename, LoggingTestConfigFilename) {
  auto test_params = GetParam();

  TempDirectory tmp_dir;
  auto conf_params = get_DEFAULT_defaults();
  conf_params["logging_folder"] = tmp_dir.name();

  TempDirectory conf_dir("conf");
  const std::string conf_text =
      "[routertestplugin_logger]\n\n" + test_params.logger_config;
  const std::string conf_file =
      create_config_file(conf_dir.name(), conf_text, &conf_params);

  auto &router = ProcessManager::launch_router({"-c", conf_file});
  router.send_clean_shutdown_event();
  check_exit_code(router, EXIT_SUCCESS);

  // check the file log if it contains what's expected
  const std::string file_log_txt =
      router.get_logfile_content(test_params.filename, tmp_dir.name());

  // check the routertestplugin_logger's message is in the logfile.
  EXPECT_THAT(file_log_txt, HasSubstr("I'm a system message"))
      << "\file_log_txt:\n"
      << file_log_txt;
}

INSTANTIATE_TEST_SUITE_P(
    LoggingTestConfigFilename, RouterLoggingTestConfigFilename,
    ::testing::Values(
        // default filename in logger section
        /*0*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "filename=" DEFAULT_LOGFILE_NAME "\n",
                                      DEFAULT_LOGFILE_NAME),
        // TS_FR01_01 user defined logfile name in logger section
        /*1*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "filename=" USER_LOGFILE_NAME "\n",
                                      USER_LOGFILE_NAME),
        // TS_FR01_02 user defined logfile name in filelog sink
        /*2*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "sinks=filelog\n"
                                      "[filelog]\n"
                                      "filename=" USER_LOGFILE_NAME "\n",
                                      USER_LOGFILE_NAME),
        // TS_FR04_09 user defined logfile name in filelog sink overrides user
        // defined logfile name in logger section
        /*3*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "sinks=filelog\n"
                                      "filename=" USER_LOGFILE_NAME "\n"
                                      "[filelog]\n"
                                      "filename=" USER_LOGFILE_NAME_2 "\n",
                                      USER_LOGFILE_NAME_2),
        // TS_FR05_01 empty logger filename logs to default logfile name
        /*4*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "filename=\n",
                                      DEFAULT_LOGFILE_NAME),
        // TS_FR05_02 empty filelog filename logs to default logfile name
        /*5*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "sinks=filelog\n"
                                      "[filelog]\n"
                                      "filename=\n",
                                      DEFAULT_LOGFILE_NAME),
        // TS_FR04_11 empty filelog filename logs to userdefined logger filename
        /*6*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "filename=" USER_LOGFILE_NAME "\n"
                                      "sinks=filelog\n"
                                      "[filelog]\n"
                                      "filename=\n",
                                      USER_LOGFILE_NAME),
        // TS_FR04_12 undefined filelog filename logs to userdefined value for
        // logger filename
        /*7*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "filename=" USER_LOGFILE_NAME "\n"
                                      "sinks=filelog\n"
                                      "[filelog]\n",
                                      USER_LOGFILE_NAME),
        // user defined logfile name in filelog sink overrides logger section
        /*8*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "sinks=filelog\n"
                                      "filename=" DEFAULT_LOGFILE_NAME "\n"
                                      "[filelog]\n"
                                      "filename=" USER_LOGFILE_NAME "\n",
                                      USER_LOGFILE_NAME),
        // TS_FR04_01 empty filename has no effect
        /*9*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "sinks=filelog\n"
                                      "filename=\n"
                                      "[filelog]\n"
                                      "filename=" USER_LOGFILE_NAME_2 "\n",
                                      USER_LOGFILE_NAME_2),
        // TS_FR04_03 empty filenames has no effect, and logs to default
        /*10*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "sinks=filelog\n"
                                      "filename=\n"
                                      "[filelog]\n"
                                      "filename=\n",
                                      DEFAULT_LOGFILE_NAME),
        // TS_FR04_04 no filenames results in logging to default
        /*11*/
        LoggingConfigFilenameOkParams("[logger]\n"
                                      "sinks=filelog\n"
                                      "[filelog]\n",
                                      DEFAULT_LOGFILE_NAME)));

#define NOT_USED ""

#ifndef _WIN32
#define NULL_DEVICE_NAME "/dev/null"
#define STDOUT_DEVICE_NAME "/dev/stdout"
#define STDERR_DEVICE_NAME "/dev/stderr"
#else
#define NULL_DEVICE_NAME "NUL"
#define STDOUT_DEVICE_NAME "CON"
// No STDERR equivalent for WIN32
#endif

class RouterLoggingTestConfigFilenameDevices
    : public RouterLoggingTest,
      public ::testing::WithParamInterface<LoggingConfigFilenameOkParams> {};

/** @test This test verifies that consolelog destination may be set to various
 * devices
 */
TEST_P(RouterLoggingTestConfigFilenameDevices,
       LoggingTestConsoleDestinationDevices) {
  // FIXME: Unfortunately due to the limitations of our component testing
  // framework, this test has a flaw: it is not possible to distinguish if the
  // output returned from router.get_full_output() appeared on STDERR or STDOUT.
  // This should be fixed in the future.
  auto test_params = GetParam();
  bool console_empty =
      (test_params.filename.compare(NULL_DEVICE_NAME) == 0 ? true : false);

  Path destination(test_params.filename);
#ifndef _WIN32
  EXPECT_TRUE(destination.exists());
#endif

  TempDirectory tmp_dir;
  auto conf_params = get_DEFAULT_defaults();
  conf_params["logging_folder"] = tmp_dir.name();

  TempDirectory conf_dir("conf");
  const std::string conf_text =
      "[routing]\n"
      "\n"
      "[logger]\n"
      "sinks=consolelog\n"
      "[consolelog]\n"
      "destination=" +
      destination.str();
  const std::string conf_file =
      create_config_file(conf_dir.name(), conf_text, &conf_params);

  // empty routing section results in a failure, but while logging to file
  auto &router = launch_router({"-c", conf_file}, EXIT_FAILURE,
                               test_params.console_to_stderr, false, -1s);
  check_exit_code(router, EXIT_FAILURE);

  const std::string console_log_txt = router.get_full_output();
  if (console_empty) {
    // Expect the console log to be empty
    EXPECT_TRUE(console_log_txt.empty()) << "\nconsole:\n" << console_log_txt;
  } else {
    // Expect the console log to not be empty
    EXPECT_TRUE(!console_log_txt.empty()) << "\nconsole:\n" << console_log_txt;
  }

  // expect no default router file created in the logging folder
  Path shouldnotexist = Path(tmp_dir.name()).join(DEFAULT_LOGFILE_NAME);
  EXPECT_FALSE(shouldnotexist.exists());
  shouldnotexist = Path("/dev").join(DEFAULT_LOGFILE_NAME);
  EXPECT_FALSE(shouldnotexist.exists());

#ifndef _WIN32
  EXPECT_TRUE(destination.exists());
#endif
}

INSTANTIATE_TEST_SUITE_P(
    LoggingTestConsoleDestinationDevices,
    RouterLoggingTestConfigFilenameDevices,
    ::testing::Values(
        // TS_FR07_03 consolelog destination /dev/null
        /*0*/
        LoggingConfigFilenameOkParams(NOT_USED, NULL_DEVICE_NAME, true),
        // TS_FR07_01 consolelog destination /dev/stdout
        /*1*/
        LoggingConfigFilenameOkParams(NOT_USED, STDOUT_DEVICE_NAME, false)));

#ifndef _WIN32
INSTANTIATE_TEST_SUITE_P(
    LoggingTestConsoleDestinationDevicesUnix,
    RouterLoggingTestConfigFilenameDevices,
    ::testing::Values(
        // TS_FR07_02 consolelog destination /dev/stderr
        /*0*/
        LoggingConfigFilenameOkParams(NOT_USED, STDERR_DEVICE_NAME, true)));
#endif

struct LoggingConfigFilenameErrorParams {
  std::string logger_config;
  std::string filename;
  bool create_file;
  std::string expected_error;

  LoggingConfigFilenameErrorParams(const std::string &logger_config_,
                                   const std::string filename_,
                                   bool create_file_,
                                   const std::string expected_error_)
      : logger_config(logger_config_),
        filename(filename_),
        create_file(create_file_),
        expected_error(expected_error_) {}
};

class RouterLoggingConfigFilenameError
    : public RouterLoggingTest,
      public ::testing::WithParamInterface<LoggingConfigFilenameErrorParams> {};

#define ABS_PATH "%%ABSPATH%%"
#define ABS_DIR "%%ABSDIR%%"
#define REL_PATH "%%RELPATH%%"
#define REL_DIR "%%RELDIR%%"
#define FILENAME "%%FILENAME%%"

/** @test This test verifies that absolute and relative filenames are rejected
 * in filename option for various sinks/filename combinations.
 */
TEST_P(RouterLoggingConfigFilenameError, LoggingConfigAbsRelFilenameError) {
  auto test_params = GetParam();

  TempDirectory tmp_dir;

  // create the absolute and relative paths (note: order)
  Path abs_dir = Path(tmp_dir.name()).real_path();
  Path abs_path = abs_dir.join(test_params.filename);
  Path rel_path = Path(tmp_dir.name()).basename().join(test_params.filename);

  auto conf_params = get_DEFAULT_defaults();
  conf_params["logging_folder"] = abs_dir.str();

  // Create tmp_file once the tmp_dir is created. Removed by tmp_dir dtor.
  if (test_params.create_file) {
    std::ofstream myfile_;
    myfile_.open(abs_path.str());
    if (myfile_.is_open()) {
      myfile_ << "Temporary file created by router test ...\n";
      myfile_.flush();
      myfile_.close();
    }
    EXPECT_TRUE(abs_path.exists());
  }

  // replace the pattern in config where applicable
  std::string cfg = "[keepalive]\n\n" + test_params.logger_config;
  while (cfg.find(FILENAME) != std::string::npos) {
    cfg.replace(cfg.find(FILENAME), sizeof(FILENAME) - 1,
                test_params.filename.c_str());
  }
  while (cfg.find(ABS_PATH) != std::string::npos) {
    cfg.replace(cfg.find(ABS_PATH), sizeof(ABS_PATH) - 1, abs_path.c_str());
  }
  while (cfg.find(ABS_DIR) != std::string::npos) {
    cfg.replace(cfg.find(ABS_DIR), sizeof(ABS_DIR) - 1, abs_dir.c_str());
  }
  while (cfg.find(REL_PATH) != std::string::npos) {
    cfg.replace(cfg.find(REL_PATH), sizeof(REL_PATH) - 1, rel_path.c_str());
  }

  TempDirectory conf_dir("conf");
  const std::string conf_file =
      create_config_file(conf_dir.name(), cfg, &conf_params);

  // empty routing section results in a failure, but while logging to file
  auto &router = launch_router_for_fail({"-c", conf_file});
  check_exit_code(router, EXIT_FAILURE);

  // the error happens during the logger initialization so we expect the message
  // on the console which is the default sink until we switch to the
  // configuration from the config file
  const std::string console_log_txt = router.get_full_output();

  EXPECT_TRUE(!console_log_txt.empty()) << "\nconsole:\n" << console_log_txt;

  EXPECT_THAT(console_log_txt, HasSubstr(test_params.expected_error))
      << "\nconsole:\n"
      << console_log_txt;

  // expect no default router file created in the logging folder
  Path shouldnotexist = Path(abs_dir.str()).join(DEFAULT_LOGFILE_NAME);
  EXPECT_FALSE(shouldnotexist.exists());

  if (!test_params.create_file) {
    EXPECT_FALSE(abs_path.exists());
  }
}

INSTANTIATE_TEST_SUITE_P(
    LoggingConfigAbsRelFilenameError, RouterLoggingConfigFilenameError,
    ::testing::Values(
        // TS_FR02_01 filename with relative path in logger
        /*0*/ LoggingConfigFilenameErrorParams(
            "[logger]\n"
            "filename=" REL_PATH "\n",
            USER_LOGFILE_NAME, false, "must be a filename, not a path"),
        // TS_FR02_02 filename with relative path in filelog
        /*1*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=filelog\n"
                                         "[filelog]\n"
                                         "filename=" REL_PATH "\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR02_03 absolute filename in logger
        /*2*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "filename=" ABS_PATH "\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR02_04 absolute filename in filelog
        /*3*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=filelog\n"
                                         "[filelog]\n"
                                         "filename=" ABS_PATH "\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR02_05 slash filename in logger
        /*4*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "filename=/\n",
                                         USER_LOGFILE_NAME, false,
                                         "is not a valid log filename"),
        // TS_FR02_06 slash filename in filelog
        /*5*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=filelog\n"
                                         "[filelog]\n"
                                         "filename=/\n",
                                         USER_LOGFILE_NAME, false,
                                         "is not a valid log filename"),
        // TS_FR02_07 existing folder filename in filelog
        /*6*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "filename=" ABS_DIR "\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR02_08 existing folder filename in filelog
        /*7*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=filelog\n"
                                         "[filelog]\n"
                                         "filename=" ABS_DIR "\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR02_09 dot filename in logger
        /*8*/
        LoggingConfigFilenameErrorParams(
            "[logger]\n"
            "filename=.\n",
            USER_LOGFILE_NAME, false,
            "File exists, but cannot open for writing"),
        // TS_FR02_10 dot filename in filelog
        /*9*/
        LoggingConfigFilenameErrorParams(
            "[logger]\n"
            "sinks=filelog\n"
            "[filelog]\n"
            "filename=.\n",
            USER_LOGFILE_NAME, false,
            "File exists, but cannot open for writing"),
        // TS_FR04_10 filename /path triggers warning and not silent override
        /*10*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "filename=" USER_LOGFILE_NAME "\n"
                                         "sinks=filelog\n"
                                         "[filelog]\n"
                                         "filename=" ABS_DIR "\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR04_02 empty filename has no effect
        /*11*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "filename=\n"
                                         "sinks=filelog\n"
                                         "[filelog]\n"
                                         "filename=" ABS_DIR "\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR04_06 Verify [logger].filename=/path or [filelog].filename
        // triggers an error
        /*12*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "filename=" ABS_DIR "\n"
                                         "sinks=filelog\n"
                                         "[filelog]\n"
                                         "filename=" ABS_DIR "\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR04_07 Verify [logger].filename=/path triggers an error
        /*13*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "filename=" ABS_DIR "\n"
                                         "sinks=filelog\n"
                                         "[filelog]\n"
                                         "filename=\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR04_08 Verify [logger].filename=/path triggers an error
        /*14*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "filename=" ABS_DIR "\n"
                                         "sinks=filelog\n"
                                         "[filelog]\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR10_01 consolelog destination set to existing file
        /*15*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=consolelog\n"
                                         "[consolelog]\n"
                                         "destination=" FILENAME "\n",
                                         USER_LOGFILE_NAME, true,
                                         "Illegal destination"),
        // TS_FR10_02 consolelog destination set to non-existing file
        /*16*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=consolelog\n"
                                         "[consolelog]\n"
                                         "destination=" FILENAME "\n",
                                         USER_LOGFILE_NAME, false,
                                         "Illegal destination"),
        // TS_FR10_03 consolelog destination set to relative file
        /*17*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=consolelog\n"
                                         "[consolelog]\n"
                                         "destination=" REL_PATH "\n",
                                         USER_LOGFILE_NAME, true,
                                         "Illegal destination"),
        // TS_FR10_04 consolelog destination set to relative file
        /*18*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=consolelog\n"
                                         "[consolelog]\n"
                                         "destination=" ABS_PATH "\n",
                                         USER_LOGFILE_NAME, true,
                                         "Illegal destination"),
        // TS_FR10_05 consolelog destination set to relative file
        /*19*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=consolelog\n"
                                         "[consolelog]\n"
                                         "destination=" ABS_DIR "\n",
                                         USER_LOGFILE_NAME, false,
                                         "Illegal destination"),
        // TS_FR04_05 absolute path in logger and legal filename fails
        /*20*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=filelog\n"
                                         "filename=" ABS_DIR "\n"
                                         "[filelog]\n"
                                         "filename=" USER_LOGFILE_NAME "\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR04_05a corner case
        /*21*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=filelog\n"
                                         "filename=/shouldfail.log\n"
                                         "[filelog]\n"
                                         "filename=" USER_LOGFILE_NAME "\n",
                                         USER_LOGFILE_NAME, false,
                                         "must be a filename, not a path"),
        // TS_FR04_06a corner case
        /*22*/
        LoggingConfigFilenameErrorParams("[logger]\n"
                                         "sinks=filelog\n"
                                         "filename=" USER_LOGFILE_NAME "\n"
                                         "[filelog]\n"
                                         "filename=/shouldfail.log\n",
                                         USER_LOGFILE_NAME, false,
                                         "is not a valid log filename")));

struct LoggingConfigFilenameLoggingFolderParams {
  std::string logging_folder;
  std::string logger_config;
  std::string filename;
  bool catch_stderr;
  std::string expected_error;

  LoggingConfigFilenameLoggingFolderParams(const std::string &logging_folder_,
                                           const std::string &logger_config_,
                                           const std::string &filename_,
                                           bool catch_stderr_,
                                           const std::string expected_error_)
      : logging_folder(logging_folder_),
        logger_config(logger_config_),
        filename(filename_),
        catch_stderr(catch_stderr_),
        expected_error(expected_error_) {}
};

class TempRelativeDirectory {
 public:
  explicit TempRelativeDirectory(const std::string &prefix = "router")
      : name_{get_tmp_dir_(prefix)} {}

  ~TempRelativeDirectory() { mysql_harness::delete_dir_recursive(name_); }

  std::string name() const { return name_; }

 private:
  std::string name_;

#ifndef _WIN32
  // mysql_harness::get_tmp_dir() returns a relative path on these platforms
  std::string get_tmp_dir_(const std::string &name) {
    return mysql_harness::get_tmp_dir(name);
  }
#else
  // mysql_harness::get_tmp_dir() returns an abs path under GetTempPath() on
  // WIN32
  std::string get_tmp_dir_(const std::string &name) {
    auto generate_random_sequence = [](size_t len) -> std::string {
      std::random_device rd;
      std::string result;
      static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
      std::uniform_int_distribution<unsigned long> dist(0,
                                                        sizeof(alphabet) - 2);

      for (size_t i = 0; i < len; ++i) {
        result += alphabet[dist(rd)];
      }

      return result;
    };

    std::string dir_name = name + "-" + generate_random_sequence(10);
    std::string result = Path(dir_name).str();
    int err = _mkdir(result.c_str());
    if (err != 0) {
      throw std::runtime_error("Error creating temporary directory " + result);
    }
    return result;
  }
#endif
};

class RouterLoggingTestConfigFilenameLoggingFolder
    : public RouterLoggingTest,
      public ::testing::WithParamInterface<
          LoggingConfigFilenameLoggingFolderParams> {};

/** @test This test verifies that consolelog destination may be set to various
 * devices
 */
TEST_P(RouterLoggingTestConfigFilenameLoggingFolder, check) {
  auto test_params = GetParam();

  TempRelativeDirectory tmp_dir;

  // create the absolute path (note: order)
  Path abs_dir = Path(tmp_dir.name()).real_path();
  Path rel_dir = Path(tmp_dir.name()).basename();

  // Replace logging_folder tag with temporary directory
  std::string lf = test_params.logging_folder;
  while (lf.find(ABS_DIR) != std::string::npos) {
    lf.replace(lf.find(ABS_DIR), sizeof(ABS_DIR) - 1, abs_dir.c_str());
  }
  while (lf.find(REL_DIR) != std::string::npos) {
    lf.replace(lf.find(REL_DIR), sizeof(REL_DIR) - 1, rel_dir.c_str());
  }

  auto conf_params = get_DEFAULT_defaults();
  conf_params["logging_folder"] = lf;

  TempDirectory conf_dir("conf");
  const std::string cfg = "[routing]\n\n" + test_params.logger_config;
  const std::string conf_file =
      create_config_file(conf_dir.name(), cfg, &conf_params);

  // empty routing section gives failure while logging to defined sink
  auto &router = launch_router({"-c", conf_file}, EXIT_FAILURE,
                               test_params.catch_stderr, false, -1s);
  check_exit_code(router, EXIT_FAILURE);

  const std::string console_log_txt = router.get_full_output();
  if (test_params.expected_error.empty()) {
    // expect something like this as error message on console/in log
    // 2020-03-19 10:00:00 main ERROR [7f539f628780] Configuration error: option
    // destinations in [routing] is required
    const std::string errmsg = "option destinations in [routing] is required";

    if (lf.empty()) {
      // log should go to consolelog, and contain routing error
      Path logfile = rel_dir.join(test_params.filename);
      EXPECT_TRUE(!console_log_txt.empty()) << "\nconsole:\n"
                                            << console_log_txt;
      EXPECT_FALSE(logfile.exists());
      EXPECT_THAT(console_log_txt, HasSubstr(errmsg)) << "\nconsole:\n"
                                                      << console_log_txt;
    } else {
      // log should go to logfile specified
      Path logfile = Path(lf).join(test_params.filename);
      EXPECT_TRUE(console_log_txt.empty()) << "\nconsole:\n" << console_log_txt;
      EXPECT_TRUE(logfile.exists());
      std::string file_log_txt =
          router.get_logfile_content(test_params.filename, Path(lf).str());
      EXPECT_THAT(file_log_txt, HasSubstr(errmsg)) << "\nlog:\n"
                                                   << file_log_txt;
    }
  } else {
    // log should go to consolelog, and contain routing error
    EXPECT_TRUE(!console_log_txt.empty()) << "\nconsole:\n" << console_log_txt;
    EXPECT_THAT(console_log_txt, HasSubstr(test_params.expected_error))
        << "\nconsole:\n"
        << console_log_txt;
  }
}

INSTANTIATE_TEST_SUITE_P(
    LoggingTestConsoleDestinationDevices,
    RouterLoggingTestConfigFilenameLoggingFolder,
    ::testing::Values(
        // TS_FR03_01
        /*0*/
        LoggingConfigFilenameLoggingFolderParams("",
                                                 "[logger]\n"
                                                 "filename=" USER_LOGFILE_NAME
                                                 "\n",
                                                 USER_LOGFILE_NAME, true,
                                                 NOT_USED),
        // TS_FR03_02
        /*1*/
        LoggingConfigFilenameLoggingFolderParams(
            ABS_DIR, "[logger]\nfilename=" USER_LOGFILE_NAME "\n",
            USER_LOGFILE_NAME, false, NOT_USED),
        // TS_FR03_03
        /*2*/
        LoggingConfigFilenameLoggingFolderParams(
            REL_DIR, "[logger]\nfilename=" USER_LOGFILE_NAME "\n",
            USER_LOGFILE_NAME, false, NOT_USED),
        // TS_FR03_04
        /*3*/
        LoggingConfigFilenameLoggingFolderParams(
            "/non/existing/absolute/path/",
            "[logger]\nfilename=" USER_LOGFILE_NAME "\n", USER_LOGFILE_NAME,
            true, "Error when creating dir '/non/existing/absolute/path'"),
        // TS_FR03_05
        /*4*/
        LoggingConfigFilenameLoggingFolderParams(
            "non/existing/relative/path",
            "[logger]\nfilename=" USER_LOGFILE_NAME "\n", USER_LOGFILE_NAME,
            true, "Error when creating dir 'non/existing/relative/path'"),
        // TS_FR05_03 without [logger].filename
        // and TS_FR05_04 without [filesink].filename
        /*5*/
        LoggingConfigFilenameLoggingFolderParams(
            ABS_DIR, "[logger]\nsinks=filelog\n[filelog]\n",
            DEFAULT_LOGFILE_NAME, false, NOT_USED)));

/** @test This test verifies that output goes to console when consolelog
 * destination is empty (TS_FR06_01)
 */
TEST_F(RouterLoggingTest, log_console_destination_empty) {
  // FIXME: Unfortunately due to the limitations of our component testing
  // framework, this test has a flaw: it is not possible to distinguish if the
  // output returned from router.get_full_output() appeared on STDERR or STDOUT.
  // This should be fixed in the future.
  TempDirectory tmp_dir;
  auto conf_params = get_DEFAULT_defaults();
  conf_params["logging_folder"] = tmp_dir.name();

  TempDirectory conf_dir("conf");
  const std::string conf_text =
      "[routing]\n\n[logger]\nsinks=consolelog\n[consolelog]\ndestination=";
  const std::string conf_file =
      create_config_file(conf_dir.name(), conf_text, &conf_params);

  // empty routing section results in a failure, but while logging to
  // destination
  auto &router = launch_router_for_fail({"-c", conf_file});
  check_exit_code(router, EXIT_FAILURE);

  // Expect the console log to be used on empty destinaton
  const std::string console_log_txt = router.get_full_output();
  EXPECT_FALSE(console_log_txt.empty()) << "\nconsole:\n" << console_log_txt;

  // expect no default router file created in tmp_dir
  Path shouldnotexist = Path(tmp_dir.name()).join("mysqlrouter.log");
  EXPECT_FALSE(shouldnotexist.exists());
}

/** @test This test verifies that output to console does not contain a warning
 * or the userdefined logfile name when filename not in use (TS_FR08_01)
 */
TEST_F(RouterLoggingTest, log_console_unused_filename_no_warning) {
  // FIXME: Unfortunately due to the limitations of our component testing
  // framework, this test has a flaw: it is not possible to distinguish if the
  // output returned from router.get_full_output() appeared on STDERR or STDOUT.
  // This should be fixed in the future.
  TempDirectory tmp_dir;
  auto conf_params = get_DEFAULT_defaults();
  conf_params["logging_folder"] = tmp_dir.name();

  TempDirectory conf_dir("conf");

  auto writer = config_writer(conf_dir.name())
                    .section("routing", {})
                    .section("logger", {{"filename", USER_LOGFILE_NAME},
                                        {"sinks", "consolelog"}})
                    .section("consolelog", {});

  // empty routing section results in a failure, but while logging to
  // destination
  auto &router = launch_router_for_fail({"-c", writer.write()});
  check_exit_code(router, EXIT_FAILURE);

  // Expect the console log output to NOT contain warning or log file name
  const std::string console_log_txt = router.get_full_output();
  EXPECT_FALSE(console_log_txt.empty()) << "\nconsole:\n" << console_log_txt;

  EXPECT_THAT(console_log_txt, Not(HasSubstr(USER_LOGFILE_NAME)))
      << "\nconsole:\n"
      << console_log_txt;

  EXPECT_THAT(console_log_txt, Not(HasSubstr("warning"))) << "\nconsole:\n"
                                                          << console_log_txt;
}

/** @test This test verifies non-existing [consolelog].destination uses default
 * value. i.e console (TS_FR06_02)
 */
TEST_F(RouterLoggingTest, log_console_non_existing_destination) {
  TempDirectory conf_dir("conf");

  auto writer = config_writer(conf_dir.name())
                    .section("routing", {})
                    .section("logger", {{"sinks", "consolelog"}})
                    .section("consolelog", {});

  writer.sections().at("DEFAULT")["logging_folder"] = "";

  // empty routing section results in a failure, but while logging to
  // destination
  auto &router = launch_router_for_fail({"-c", writer.write()});
  ASSERT_NO_FATAL_FAILURE(check_exit_code(router, EXIT_FAILURE));

  // Expect the console log output to NOT contain warning or log file name
  EXPECT_THAT(router.get_full_output(), ::testing::Not(::testing::IsEmpty()));
}

#ifndef _WIN32
/** @test This test verifies that filename may be set to /dev/null the ugly way
 */
TEST_F(RouterLoggingTest, log_filename_dev_null_ugly) {
  Path dev_null("/dev/null");
  EXPECT_TRUE(dev_null.exists());

  TempDirectory conf_dir("conf");

  auto writer = config_writer(conf_dir.name())
                    .section("logger", {{"filename", "null"}})
                    .section("routing", {});

  writer.sections().at("DEFAULT")["logging_folder"] = "/dev";

  // empty routing section results in a failure, but while logging to file
  auto &router = launch_router_for_fail({"-c", writer.write()});
  check_exit_code(router, EXIT_FAILURE);

  // expect no default router file created in /dev
  Path shouldnotexist("/dev/mysqlrouter.log");
  EXPECT_FALSE(shouldnotexist.exists());

  EXPECT_TRUE(dev_null.exists());
}
#endif

TEST_F(RouterLoggingTest, switch_from_main_logger_to_consolelog) {
  TempDirectory conf_dir("conf");

  auto writer = config_writer(conf_dir.name()).section("routing", {});

  // set empty logging_folder for log-to-console
  writer.sections().at("DEFAULT")["logging_folder"] = "";

  auto &router = launch_router_for_fail({"-c", writer.write()});
  ASSERT_NO_FATAL_FAILURE(check_exit_code(router, EXIT_FAILURE));

  EXPECT_THAT(router.get_full_output(), ::testing::Not(::testing::IsEmpty()));
  EXPECT_FALSE(Path(router.get_logfile_path()).exists());
}

TEST_F(RouterLoggingTest, switch_without_consolelog) {
  TempDirectory conf_dir("conf");

  // default will write to filelog.
  auto writer = config_writer(conf_dir.name()).section("routing", {});

  // no runnable config-section -> failure.
  auto &router = launch_router_for_fail({"-c", writer.write()});
  ASSERT_NO_FATAL_FAILURE(check_exit_code(router, EXIT_FAILURE));

  // only filelog should have content.
  EXPECT_THAT(router.get_full_output(), ::testing::IsEmpty());
  EXPECT_TRUE(Path(router.get_logfile_path()).exists());
  EXPECT_THAT(router.get_logfile_content(),
              ::testing::Not(::testing::IsEmpty()));
}

TEST_F(RouterLoggingTest, switch_with_consolelog) {
  TempDirectory conf_dir("conf");

  auto writer = config_writer(conf_dir.name())
                    .section("routing", {})
                    .section("logger", {{"sinks", "consolelog,filelog"}});

  // empty routing section results in a failure, but while logging to
  // destination
  auto &router = launch_router_for_fail({"-c", writer.write()});
  ASSERT_NO_FATAL_FAILURE(check_exit_code(router, EXIT_FAILURE));

  // both should have content.
  EXPECT_THAT(router.get_full_output(), ::testing::Not(::testing::IsEmpty()));
  EXPECT_THAT(router.get_full_output(),
              ::testing::Not(::testing::HasSubstr("stopping to log")));
  EXPECT_THAT(router.get_logfile_content(),
              ::testing::Not(::testing::IsEmpty()));
}

int main(int argc, char *argv[]) {
  init_windows_sockets();
  ProcessManager::set_origin(Path(argv[0]).dirname());
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}