forked from eBay/NuRaft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.cc
1282 lines (1086 loc) · 37.4 KB
/
logger.cc
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
/************************************************************************
Modifications Copyright 2017-present eBay Inc.
Author/Developer(s): Jung-Sang Ahn
Original Copyright 2017 Jung-Sang Ahn
See URL: https://github.com/greensky00/simple_logger
(v0.3.28)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**************************************************************************/
#include "logger.h"
#if defined(__linux__) || defined(__APPLE__)
#include "backtrace.h"
#endif
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <assert.h>
#if defined(__linux__) || defined(__APPLE__)
#include <dirent.h>
#ifdef __linux__
#include <pthread.h>
#endif
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#elif defined(WIN32) || defined(_WIN32)
#include <Windows.h>
#undef min
#undef max
#endif
#include <stdlib.h>
#include <string.h>
#ifndef _CLM_DEFINED
#define _CLM_DEFINED (1)
#ifdef LOGGER_NO_COLOR
#define _CLM_D_GRAY ""
#define _CLM_GREEN ""
#define _CLM_B_GREEN ""
#define _CLM_RED ""
#define _CLM_B_RED ""
#define _CLM_BROWN ""
#define _CLM_B_BROWN ""
#define _CLM_BLUE ""
#define _CLM_B_BLUE ""
#define _CLM_MAGENTA ""
#define _CLM_B_MAGENTA ""
#define _CLM_CYAN ""
#define _CLM_END ""
#define _CLM_WHITE_FG_RED_BG ""
#else
#define _CLM_D_GRAY "\033[1;30m"
#define _CLM_GREEN "\033[32m"
#define _CLM_B_GREEN "\033[1;32m"
#define _CLM_RED "\033[31m"
#define _CLM_B_RED "\033[1;31m"
#define _CLM_BROWN "\033[33m"
#define _CLM_B_BROWN "\033[1;33m"
#define _CLM_BLUE "\033[34m"
#define _CLM_B_BLUE "\033[1;34m"
#define _CLM_MAGENTA "\033[35m"
#define _CLM_B_MAGENTA "\033[1;35m"
#define _CLM_CYAN "\033[36m"
#define _CLM_B_GREY "\033[1;37m"
#define _CLM_END "\033[0m"
#define _CLM_WHITE_FG_RED_BG "\033[37;41m"
#endif
#define _CL_D_GRAY(str) _CLM_D_GRAY str _CLM_END
#define _CL_GREEN(str) _CLM_GREEN str _CLM_END
#define _CL_RED(str) _CLM_RED str _CLM_END
#define _CL_B_RED(str) _CLM_B_RED str _CLM_END
#define _CL_MAGENTA(str) _CLM_MAGENTA str _CLM_END
#define _CL_BROWN(str) _CLM_BROWN str _CLM_END
#define _CL_B_BROWN(str) _CLM_B_BROWN str _CLM_END
#define _CL_B_BLUE(str) _CLM_B_BLUE str _CLM_END
#define _CL_B_MAGENTA(str) _CLM_B_MAGENTA str _CLM_END
#define _CL_CYAN(str) _CLM_CYAN str _CLM_END
#define _CL_B_GRAY(str) _CLM_B_GREY str _CLM_END
#define _CL_WHITE_FG_RED_BG(str) _CLM_WHITE_FG_RED_BG str _CLM_END
#endif
std::atomic<SimpleLoggerMgr*> SimpleLoggerMgr::instance(nullptr);
std::mutex SimpleLoggerMgr::instanceLock;
std::mutex SimpleLoggerMgr::displayLock;
// Number of digits to represent thread IDs (Linux only).
std::atomic<int> tid_digits(2);
struct SimpleLoggerMgr::CompElem {
CompElem(uint64_t num, SimpleLogger* logger)
: fileNum(num), targetLogger(logger)
{}
uint64_t fileNum;
SimpleLogger* targetLogger;
};
SimpleLoggerMgr::TimeInfo::TimeInfo(std::tm* src)
: year(src->tm_year + 1900)
, month(src->tm_mon + 1)
, day(src->tm_mday)
, hour(src->tm_hour)
, min(src->tm_min)
, sec(src->tm_sec)
, msec(0)
, usec(0)
{}
SimpleLoggerMgr::TimeInfo::TimeInfo(std::chrono::system_clock::time_point now) {
std::time_t raw_time = std::chrono::system_clock::to_time_t(now);
std::tm new_time;
#if defined(__linux__) || defined(__APPLE__)
std::tm* lt_tm = localtime_r(&raw_time, &new_time);
#elif defined(WIN32) || defined(_WIN32)
localtime_s(&new_time, &raw_time);
std::tm* lt_tm = &new_time;
#endif
year = lt_tm->tm_year + 1900;
month = lt_tm->tm_mon + 1;
day = lt_tm->tm_mday;
hour = lt_tm->tm_hour;
min = lt_tm->tm_min;
sec = lt_tm->tm_sec;
size_t us_epoch = std::chrono::duration_cast< std::chrono::microseconds >
( now.time_since_epoch() ).count();
msec = (us_epoch / 1000) % 1000;
usec = us_epoch % 1000;
}
SimpleLoggerMgr* SimpleLoggerMgr::init() {
SimpleLoggerMgr* mgr = instance.load(SimpleLogger::MOR);
if (!mgr) {
std::lock_guard<std::mutex> l(instanceLock);
mgr = instance.load(SimpleLogger::MOR);
if (!mgr) {
mgr = new SimpleLoggerMgr();
instance.store(mgr, SimpleLogger::MOR);
}
}
return mgr;
}
SimpleLoggerMgr* SimpleLoggerMgr::get() {
SimpleLoggerMgr* mgr = instance.load(SimpleLogger::MOR);
if (!mgr) return init();
return mgr;
}
SimpleLoggerMgr* SimpleLoggerMgr::getWithoutInit() {
SimpleLoggerMgr* mgr = instance.load(SimpleLogger::MOR);
return mgr;
}
void SimpleLoggerMgr::destroy() {
std::lock_guard<std::mutex> l(instanceLock);
SimpleLoggerMgr* mgr = instance.load(SimpleLogger::MOR);
if (mgr) {
mgr->flushAllLoggers();
delete mgr;
instance.store(nullptr, SimpleLogger::MOR);
}
}
int SimpleLoggerMgr::getTzGap() {
std::chrono::system_clock::time_point now =
std::chrono::system_clock::now();
std::time_t raw_time = std::chrono::system_clock::to_time_t(now);
std::tm new_time;
#if defined(__linux__) || defined(__APPLE__)
std::tm* lt_tm = localtime_r(&raw_time, &new_time);
std::tm* gmt_tm = std::gmtime(&raw_time);
#elif defined(WIN32) || defined(_WIN32)
localtime_s(&new_time, &raw_time);
std::tm* lt_tm = &new_time;
std::tm new_gmt_time;
gmtime_s(&new_gmt_time, &raw_time);
std::tm* gmt_tm = &new_gmt_time;
#endif
TimeInfo lt(lt_tm);
TimeInfo gmt(gmt_tm);
return ( ( lt.day * 60 * 24 + lt.hour * 60 + lt.min ) -
( gmt.day * 60 * 24 + gmt.hour * 60 + gmt.min ) );
}
// LCOV_EXCL_START
void SimpleLoggerMgr::flushCriticalInfo() {
std::string msg = " === Critical info (given by user): ";
msg += std::to_string(globalCriticalInfo.size()) + " bytes";
msg += " ===";
if (!globalCriticalInfo.empty()) {
msg += "\n" + globalCriticalInfo;
}
flushAllLoggers(2, msg);
if (crashDumpFile.is_open()) {
crashDumpFile << msg << std::endl << std::endl;
}
}
void SimpleLoggerMgr::_flushStackTraceBuffer(size_t buffer_len,
uint32_t tid_hash,
uint64_t kernel_tid,
bool crash_origin)
{
std::string msg;
char temp_buf[256];
snprintf(temp_buf, 256, "\nThread %04x", tid_hash);
msg += temp_buf;
if (kernel_tid) {
msg += " (" + std::to_string(kernel_tid) + ")";
}
if (crash_origin) {
msg += " (crashed here)";
}
msg += "\n\n";
msg += std::string(stackTraceBuffer, buffer_len);
size_t msg_len = msg.size();
size_t per_log_size = SimpleLogger::MSG_SIZE - 1024;
for (size_t ii=0; ii<msg_len; ii+=per_log_size) {
flushAllLoggers(2, msg.substr(ii, per_log_size));
}
if (crashDumpFile.is_open()) {
crashDumpFile << msg << std::endl;
}
}
void SimpleLoggerMgr::flushStackTraceBuffer(RawStackInfo& stack_info) {
#if defined(__linux__) || defined(__APPLE__)
size_t len = _stack_interpret(&stack_info.stackPtrs[0],
stack_info.stackPtrs.size(),
stackTraceBuffer,
stackTraceBufferSize);
if (!len) return;
_flushStackTraceBuffer(len,
stack_info.tidHash,
stack_info.kernelTid,
stack_info.crashOrigin);
#endif
}
void SimpleLoggerMgr::logStackBackTraceOtherThreads() {
bool got_other_stacks = false;
#ifdef __linux__
if (!crashDumpOriginOnly) {
// Not support non-Linux platform.
uint64_t my_tid = pthread_self();
uint64_t exp = 0;
if (!crashOriginThread.compare_exchange_strong(exp, my_tid)) {
// Other thread is already working on it, stop here.
return;
}
std::lock_guard<std::mutex> l(activeThreadsLock);
std::string msg = "captured ";
msg += std::to_string(activeThreads.size()) + " active threads";
flushAllLoggers(2, msg);
if (crashDumpFile.is_open()) crashDumpFile << msg << "\n\n";
for (uint64_t _tid: activeThreads) {
pthread_t tid = (pthread_t)_tid;
if (_tid == crashOriginThread) continue;
struct sigaction _action;
sigfillset(&_action.sa_mask);
_action.sa_flags = SA_SIGINFO;
_action.sa_sigaction = SimpleLoggerMgr::handleStackTrace;
sigaction(SIGUSR2, &_action, NULL);
pthread_kill(tid, SIGUSR2);
sigset_t _mask;
sigfillset(&_mask);
sigdelset(&_mask, SIGUSR2);
sigsuspend(&_mask);
}
msg = "got all stack traces, now flushing them";
flushAllLoggers(2, msg);
got_other_stacks = true;
}
#endif
if (!got_other_stacks) {
std::string msg = "will not explore other threads (disabled by user)";
flushAllLoggers(2, msg);
if (crashDumpFile.is_open()) {
crashDumpFile << msg << "\n\n";
}
}
}
void SimpleLoggerMgr::flushRawStack(RawStackInfo& stack_info) {
if (!crashDumpFile.is_open()) return;
crashDumpFile << "Thread " << std::hex << std::setw(4) << std::setfill('0')
<< stack_info.tidHash << std::dec
<< " " << stack_info.kernelTid << std::endl;
if (stack_info.crashOrigin) {
crashDumpFile << "(crashed here)" << std::endl;
}
for (void* stack_ptr: stack_info.stackPtrs) {
crashDumpFile << std::hex << stack_ptr << std::dec << std::endl;
}
crashDumpFile << std::endl;
}
void SimpleLoggerMgr::addRawStackInfo(bool crash_origin) {
#if defined(__linux__) || defined(__APPLE__)
void* stack_ptr[256];
size_t len = _stack_backtrace(stack_ptr, 256);
crashDumpThreadStacks.push_back(RawStackInfo());
RawStackInfo& stack_info = *(crashDumpThreadStacks.rbegin());
std::thread::id tid = std::this_thread::get_id();
stack_info.tidHash = std::hash<std::thread::id>{}(tid) % 0x10000;
#ifdef __linux__
stack_info.kernelTid = (uint64_t)syscall(SYS_gettid);
#endif
stack_info.crashOrigin = crash_origin;
for (size_t ii=0; ii<len; ++ii) {
stack_info.stackPtrs.push_back(stack_ptr[ii]);
}
#endif
}
void SimpleLoggerMgr::logStackBacktrace(size_t timeout_ms) {
// Set abort timeout: 60 seconds.
abortTimer = timeout_ms;
if (!crashDumpPath.empty() && !crashDumpFile.is_open()) {
// Open crash dump file.
TimeInfo lt( std::chrono::system_clock::now() );
int tz_gap = getTzGap();
int tz_gap_abs = (tz_gap < 0) ? (tz_gap * -1) : (tz_gap);
char filename[128];
snprintf(filename, 128, "dump_%04d%02d%02d_%02d%02d%02d%c%02d%02d.txt",
lt.year, lt.month, lt.day,
lt.hour, lt.min, lt.sec,
(tz_gap >= 0) ? '+' : '-',
(int)(tz_gap_abs / 60), tz_gap_abs % 60);
std::string path = crashDumpPath + "/" + filename;
crashDumpFile.open(path);
char time_fmt[64];
snprintf(time_fmt, 64, "%04d-%02d-%02dT%02d:%02d:%02d.%03d%03d%c%02d:%02d",
lt.year, lt.month, lt.day,
lt.hour, lt.min, lt.sec, lt.msec, lt.usec,
(tz_gap >= 0) ? '+' : '-',
(int)(tz_gap_abs / 60), tz_gap_abs % 60);
crashDumpFile << "When: " << time_fmt << std::endl << std::endl;
}
flushCriticalInfo();
addRawStackInfo(true);
// Collect other threads' stack info.
logStackBackTraceOtherThreads();
// Now print out.
// For the case where `addr2line` is hanging, flush raw pointer first.
for (RawStackInfo& entry: crashDumpThreadStacks) {
flushRawStack(entry);
}
for (RawStackInfo& entry: crashDumpThreadStacks) {
flushStackTraceBuffer(entry);
}
}
bool SimpleLoggerMgr::chkExitOnCrash() {
if (exitOnCrash) return true;
std::string env_segv_str;
const char* env_segv = std::getenv("SIMPLELOGGER_EXIT_ON_CRASH");
if (env_segv) env_segv_str = env_segv;
if ( env_segv_str == "ON" ||
env_segv_str == "on" ||
env_segv_str == "TRUE" ||
env_segv_str == "true" ) {
// Manually turned off by user, via env var.
return true;
}
return false;
}
void SimpleLoggerMgr::handleSegFault(int sig) {
#if defined(__linux__) || defined(__APPLE__)
SimpleLoggerMgr* mgr = SimpleLoggerMgr::get();
signal(SIGSEGV, mgr->oldSigSegvHandler);
mgr->enableOnlyOneDisplayer();
mgr->flushAllLoggers(1, "Segmentation fault");
mgr->logStackBacktrace();
printf("[SEG FAULT] Flushed all logs safely.\n");
fflush(stdout);
if (mgr->chkExitOnCrash()) {
printf("[SEG FAULT] Exit on crash.\n");
fflush(stdout);
exit(-1);
}
if (mgr->oldSigSegvHandler) {
mgr->oldSigSegvHandler(sig);
}
#endif
}
void SimpleLoggerMgr::handleSegAbort(int sig) {
#if defined(__linux__) || defined(__APPLE__)
SimpleLoggerMgr* mgr = SimpleLoggerMgr::get();
signal(SIGABRT, mgr->oldSigAbortHandler);
mgr->enableOnlyOneDisplayer();
mgr->flushAllLoggers(1, "Abort");
mgr->logStackBacktrace();
printf("[ABORT] Flushed all logs safely.\n");
fflush(stdout);
if (mgr->chkExitOnCrash()) {
printf("[ABORT] Exit on crash.\n");
fflush(stdout);
exit(-1);
}
abort();
#endif
}
#if defined(__linux__) || defined(__APPLE__)
void SimpleLoggerMgr::handleStackTrace(int sig, siginfo_t* info, void* secret) {
#ifndef __linux__
// Not support non-Linux platform.
return;
#else
SimpleLoggerMgr* mgr = SimpleLoggerMgr::get();
if (!mgr->crashOriginThread) return;
pthread_t myself = pthread_self();
if (mgr->crashOriginThread == myself) return;
// NOTE:
// As getting exact line number is too expensive,
// keep stack pointers first and then interpret it.
mgr->addRawStackInfo();
// Go back to origin thread.
pthread_kill(mgr->crashOriginThread, SIGUSR2);
#endif
}
#endif
// LCOV_EXCL_STOP
void SimpleLoggerMgr::flushWorker() {
#ifdef __linux__
pthread_setname_np(pthread_self(), "sl_flusher");
#endif
SimpleLoggerMgr* mgr = SimpleLoggerMgr::get();
while (!mgr->chkTermination()) {
// Every 500ms.
size_t sub_ms = 500;
mgr->sleepFlusher(sub_ms);
mgr->flushAllLoggers();
if (mgr->abortTimer) {
if (mgr->abortTimer > sub_ms) {
mgr->abortTimer.fetch_sub(sub_ms);
} else {
std::cerr << "STACK DUMP TIMEOUT, FORCE ABORT" << std::endl;
exit(-1);
}
}
}
}
void SimpleLoggerMgr::compressWorker() {
#ifdef __linux__
pthread_setname_np(pthread_self(), "sl_compressor");
#endif
SimpleLoggerMgr* mgr = SimpleLoggerMgr::get();
bool sleep_next_time = true;
while (!mgr->chkTermination()) {
// Every 500ms.
size_t sub_ms = 500;
if (sleep_next_time) {
mgr->sleepCompressor(sub_ms);
}
sleep_next_time = true;
CompElem* elem = nullptr;
{ std::lock_guard<std::mutex> l(mgr->pendingCompElemsLock);
auto entry = mgr->pendingCompElems.begin();
if (entry != mgr->pendingCompElems.end()) {
elem = *entry;
mgr->pendingCompElems.erase(entry);
}
}
if (elem) {
elem->targetLogger->doCompression(elem->fileNum);
delete elem;
// Continuous compression if pending item exists.
sleep_next_time = false;
}
}
}
void SimpleLoggerMgr::setCrashDumpPath(const std::string& path,
bool origin_only)
{
crashDumpPath = path;
setStackTraceOriginOnly(origin_only);
}
void SimpleLoggerMgr::setStackTraceOriginOnly(bool origin_only) {
crashDumpOriginOnly = origin_only;
}
void SimpleLoggerMgr::setExitOnCrash(bool exit_on_crash) {
exitOnCrash = exit_on_crash;
}
SimpleLoggerMgr::SimpleLoggerMgr()
: termination(false)
, oldSigSegvHandler(nullptr)
, oldSigAbortHandler(nullptr)
, stackTraceBuffer(nullptr)
, crashOriginThread(0)
, crashDumpOriginOnly(true)
, exitOnCrash(false)
, abortTimer(0)
{
#if defined(__linux__) || defined(__APPLE__)
std::string env_segv_str;
const char* env_segv = std::getenv("SIMPLELOGGER_HANDLE_SEGV");
if (env_segv) env_segv_str = env_segv;
if ( env_segv_str == "OFF" ||
env_segv_str == "off" ||
env_segv_str == "FALSE" ||
env_segv_str == "false" ) {
// Manually turned off by user, via env var.
} else {
oldSigSegvHandler = signal(SIGSEGV, SimpleLoggerMgr::handleSegFault);
oldSigAbortHandler = signal(SIGABRT, SimpleLoggerMgr::handleSegAbort);
}
stackTraceBuffer = (char*)malloc(stackTraceBufferSize);
#endif
tFlush = std::thread(SimpleLoggerMgr::flushWorker);
tCompress = std::thread(SimpleLoggerMgr::compressWorker);
}
SimpleLoggerMgr::~SimpleLoggerMgr() {
termination = true;
#if defined(__linux__) || defined(__APPLE__)
signal(SIGSEGV, oldSigSegvHandler);
signal(SIGABRT, oldSigAbortHandler);
#endif
{ std::unique_lock<std::mutex> l(cvFlusherLock);
cvFlusher.notify_all();
}
{ std::unique_lock<std::mutex> l(cvCompressorLock);
cvCompressor.notify_all();
}
if (tFlush.joinable()) {
tFlush.join();
}
if (tCompress.joinable()) {
tCompress.join();
}
free(stackTraceBuffer);
}
// LCOV_EXCL_START
void SimpleLoggerMgr::enableOnlyOneDisplayer() {
bool marked = false;
std::unique_lock<std::mutex> l(loggersLock);
for (auto& entry: loggers) {
SimpleLogger* logger = entry;
if (!logger) continue;
if (!marked) {
// The first logger: enable display
if (logger->getLogLevel() < 4) {
logger->setLogLevel(4);
}
logger->setDispLevel(4);
marked = true;
} else {
// The others: disable display
logger->setDispLevel(-1);
}
}
}
// LCOV_EXCL_STOP
void SimpleLoggerMgr::flushAllLoggers(int level, const std::string& msg) {
std::unique_lock<std::mutex> l(loggersLock);
for (auto& entry: loggers) {
SimpleLogger* logger = entry;
if (!logger) continue;
if (!msg.empty()) {
logger->put(level, __FILE__, __func__, __LINE__, "%s", msg.c_str());
}
logger->flushAll();
}
}
void SimpleLoggerMgr::addLogger(SimpleLogger* logger) {
std::unique_lock<std::mutex> l(loggersLock);
loggers.insert(logger);
}
void SimpleLoggerMgr::removeLogger(SimpleLogger* logger) {
std::unique_lock<std::mutex> l(loggersLock);
loggers.erase(logger);
}
void SimpleLoggerMgr::addThread(uint64_t tid) {
std::unique_lock<std::mutex> l(activeThreadsLock);
activeThreads.insert(tid);
}
void SimpleLoggerMgr::removeThread(uint64_t tid) {
std::unique_lock<std::mutex> l(activeThreadsLock);
activeThreads.erase(tid);
}
void SimpleLoggerMgr::addCompElem(SimpleLoggerMgr::CompElem* elem) {
{ std::unique_lock<std::mutex> l(pendingCompElemsLock);
pendingCompElems.push_back(elem);
}
{ std::unique_lock<std::mutex> l(cvCompressorLock);
cvCompressor.notify_all();
}
}
void SimpleLoggerMgr::sleepFlusher(size_t ms) {
std::unique_lock<std::mutex> l(cvFlusherLock);
cvFlusher.wait_for(l, std::chrono::milliseconds(ms));
}
void SimpleLoggerMgr::sleepCompressor(size_t ms) {
std::unique_lock<std::mutex> l(cvCompressorLock);
cvCompressor.wait_for(l, std::chrono::milliseconds(ms));
}
bool SimpleLoggerMgr::chkTermination() const {
return termination;
}
void SimpleLoggerMgr::setCriticalInfo(const std::string& info_str) {
globalCriticalInfo = info_str;
}
const std::string& SimpleLoggerMgr::getCriticalInfo() const {
return globalCriticalInfo;
}
// ==========================================
struct ThreadWrapper {
#ifdef __linux__
ThreadWrapper() {
mySelf = (uint64_t)pthread_self();
myTid = (uint32_t)syscall(SYS_gettid);
// Get the number of digits for alignment.
int num_digits = 0;
uint32_t tid = myTid;
while (tid) {
num_digits++;
tid /= 10;
}
int exp = tid_digits;
const size_t MAX_NUM_CMP = 10;
size_t count = 0;
while (exp < num_digits && count++ < MAX_NUM_CMP) {
if (tid_digits.compare_exchange_strong(exp, num_digits)) {
break;
}
exp = tid_digits;
}
SimpleLoggerMgr* mgr = SimpleLoggerMgr::getWithoutInit();
if (mgr) {
mgr->addThread(mySelf);
}
}
~ThreadWrapper() {
SimpleLoggerMgr* mgr = SimpleLoggerMgr::getWithoutInit();
if (mgr) {
mgr->removeThread(mySelf);
}
}
#else
ThreadWrapper() : myTid(0) {}
~ThreadWrapper() {}
#endif
uint64_t mySelf;
uint32_t myTid;
};
// ==========================================
SimpleLogger::LogElem::LogElem() : len(0), status(CLEAN) {
memset(ctx, 0x0, MSG_SIZE);
}
// True if dirty.
bool SimpleLogger::LogElem::needToFlush() {
return status.load(MOR) == DIRTY;
}
// True if no other thread is working on it.
bool SimpleLogger::LogElem::available() {
Status s = status.load(MOR);
return s == CLEAN || s == DIRTY;
}
int SimpleLogger::LogElem::write(size_t _len, char* msg) {
Status exp = CLEAN;
Status val = WRITING;
if (!status.compare_exchange_strong(exp, val)) return -1;
len = (_len > MSG_SIZE) ? MSG_SIZE : _len;
memcpy(ctx, msg, len);
status.store(LogElem::DIRTY);
return 0;
}
int SimpleLogger::LogElem::flush(std::ofstream& fs) {
Status exp = DIRTY;
Status val = FLUSHING;
if (!status.compare_exchange_strong(exp, val)) return -1;
fs.write(ctx, len);
status.store(LogElem::CLEAN);
return 0;
}
// ==========================================
SimpleLogger::SimpleLogger(const std::string& file_path,
size_t max_log_elems,
uint64_t log_file_size_limit,
uint32_t max_log_files)
: filePath(replaceString(file_path, "//", "/"))
, maxLogFiles(max_log_files)
, maxLogFileSize(log_file_size_limit)
, numCompJobs(0)
, curLogLevel(4)
, curDispLevel(4)
, tzGap( SimpleLoggerMgr::getTzGap() )
, cursor(0)
, logs(max_log_elems)
{
findMinMaxRevNum(minRevnum, curRevnum);
}
SimpleLogger::~SimpleLogger() {
stop();
}
void SimpleLogger::setCriticalInfo(const std::string& info_str) {
SimpleLoggerMgr* mgr = SimpleLoggerMgr::get();
if (mgr) {
mgr->setCriticalInfo(info_str);
}
}
void SimpleLogger::setCrashDumpPath(const std::string& path,
bool origin_only)
{
SimpleLoggerMgr* mgr = SimpleLoggerMgr::get();
if (mgr) {
mgr->setCrashDumpPath(path, origin_only);
}
}
void SimpleLogger::setStackTraceOriginOnly(bool origin_only) {
SimpleLoggerMgr* mgr = SimpleLoggerMgr::get();
if (mgr) {
mgr->setStackTraceOriginOnly(origin_only);
}
}
void SimpleLogger::logStackBacktrace() {
SimpleLoggerMgr* mgr = SimpleLoggerMgr::get();
if (mgr) {
mgr->enableOnlyOneDisplayer();
mgr->logStackBacktrace(0);
}
}
void SimpleLogger::shutdown() {
SimpleLoggerMgr* mgr = SimpleLoggerMgr::getWithoutInit();
if (mgr) {
mgr->destroy();
}
}
std::string SimpleLogger::replaceString( const std::string& src_str,
const std::string& before,
const std::string& after )
{
size_t last = 0;
size_t pos = src_str.find(before, last);
std::string ret;
while (pos != std::string::npos) {
ret += src_str.substr(last, pos - last);
ret += after;
last = pos + before.size();
pos = src_str.find(before, last);
}
if (last < src_str.size()) {
ret += src_str.substr(last);
}
return ret;
}
void SimpleLogger::findMinMaxRevNum( size_t& min_revnum_out,
size_t& max_revnum_out )
{
std::string dir_path = "./";
std::string file_name_only = filePath;
size_t last_pos = filePath.rfind("/");
if (last_pos != std::string::npos) {
dir_path = filePath.substr(0, last_pos);
file_name_only = filePath.substr
( last_pos + 1, filePath.size() - last_pos - 1 );
}
bool min_revnum_initialized = false;
size_t min_revnum = 0;
size_t max_revnum = 0;
#if defined(__linux__) || defined(__APPLE__)
DIR* dir_info = opendir(dir_path.c_str());
struct dirent *dir_entry = nullptr;
while ( dir_info && (dir_entry = readdir(dir_info)) ) {
std::string f_name(dir_entry->d_name);
size_t f_name_pos = f_name.rfind(file_name_only);
// Irrelavent file: skip.
if (f_name_pos == std::string::npos) continue;
findMinMaxRevNumInternal(min_revnum_initialized,
min_revnum,
max_revnum,
f_name);
}
if (dir_info) {
closedir(dir_info);
}
#elif defined(WIN32) || defined(_WIN32)
// Windows
WIN32_FIND_DATA filedata;
HANDLE hfind;
std::string query_str = dir_path + "*";
// find all files start with 'prefix'
hfind = FindFirstFile(query_str.c_str(), &filedata);
while (hfind != INVALID_HANDLE_VALUE) {
std::string f_name(filedata.cFileName);
size_t f_name_pos = f_name.rfind(file_name_only);
// Irrelavent file: skip.
if (f_name_pos != std::string::npos) {
findMinMaxRevNumInternal(min_revnum_initialized,
min_revnum,
max_revnum,
f_name);
}
if (!FindNextFile(hfind, &filedata)) {
FindClose(hfind);
hfind = INVALID_HANDLE_VALUE;
}
}
#endif
min_revnum_out = min_revnum;
max_revnum_out = max_revnum;
}
void SimpleLogger::findMinMaxRevNumInternal(bool& min_revnum_initialized,
size_t& min_revnum,
size_t& max_revnum,
std::string& f_name)
{
size_t last_dot = f_name.rfind(".");
if (last_dot == std::string::npos) return;
bool comp_file = false;
std::string ext = f_name.substr(last_dot + 1, f_name.size() - last_dot - 1);
if (ext == "gz" && f_name.size() > 7) {
// Compressed file: asdf.log.123.tar.gz => need to get 123.
f_name = f_name.substr(0, f_name.size() - 7);
last_dot = f_name.rfind(".");
if (last_dot == std::string::npos) return;
ext = f_name.substr(last_dot + 1, f_name.size() - last_dot - 1);
comp_file = true;
}
size_t revnum = atoi(ext.c_str());
max_revnum = std::max( max_revnum,
( (comp_file) ? (revnum+1) : (revnum) ) );
if (!min_revnum_initialized) {
min_revnum = revnum;
min_revnum_initialized = true;
}
min_revnum = std::min(min_revnum, revnum);
}
std::string SimpleLogger::getLogFilePath(size_t file_num) const {
if (file_num) {
return filePath + "." + std::to_string(file_num);
}
return filePath;
}
int SimpleLogger::start() {
if (filePath.empty()) return 0;
// Append at the end.
fs.open(getLogFilePath(curRevnum), std::ofstream::out | std::ofstream::app);
if (!fs) return -1;
SimpleLoggerMgr* mgr = SimpleLoggerMgr::get();
SimpleLogger* ll = this;
mgr->addLogger(ll);
_log_sys(ll, "Start logger: %s (%zu MB per file, up to %zu files)",
filePath.c_str(),
maxLogFileSize / 1024 / 1024,
maxLogFiles.load());
const std::string& critical_info = mgr->getCriticalInfo();
if (!critical_info.empty()) {
_log_info(ll, "%s", critical_info.c_str());
}
return 0;
}
int SimpleLogger::stop() {
if (fs.is_open()) {
SimpleLoggerMgr* mgr = SimpleLoggerMgr::getWithoutInit();
if (mgr) {
SimpleLogger* ll = this;
mgr->removeLogger(ll);
_log_sys(ll, "Stop logger: %s", filePath.c_str());
flushAll();