-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
logging.cc
2712 lines (2363 loc) · 91.4 KB
/
logging.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
// Copyright (c) 2024, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite()
#include "glog/logging.h"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <iomanip>
#include <iterator>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>
#include <tuple>
#include <type_traits>
#include <utility>
#include "config.h"
#include "glog/platform.h"
#include "glog/raw_logging.h"
#include "stacktrace.h"
#include "utilities.h"
#ifdef GLOG_OS_WINDOWS
# include "windows/dirent.h"
#else
# include <dirent.h> // for automatic removal of old logs
#endif
#include <fcntl.h>
#include <sys/stat.h>
#include <cctype> // for std::isspace
#include <cerrno> // for errno
#include <climits>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <regex>
#include <sstream>
#include <vector>
#ifdef HAVE__CHSIZE_S
# include <io.h> // for truncate log file
#endif
#ifdef HAVE_PWD_H
# include <pwd.h>
#endif
#ifdef HAVE_SYS_UTSNAME_H
# include <sys/utsname.h> // For uname.
#endif
#ifdef HAVE_SYSLOG_H
# include <syslog.h>
#endif
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifndef HAVE_MODE_T
typedef int mode_t;
#endif
using std::dec;
using std::hex;
using std::min;
using std::ostream;
using std::ostringstream;
using std::setfill;
using std::setw;
using std::string;
using std::vector;
using std::fclose;
using std::fflush;
using std::FILE;
using std::fprintf;
using std::fwrite;
using std::perror;
#ifdef __QNX__
using std::fdopen;
#endif
// There is no thread annotation support.
#define EXCLUSIVE_LOCKS_REQUIRED(mu)
// TODO(hamaji): consider windows
enum { PATH_SEPARATOR = '/' };
#ifndef HAVE_PREAD
static ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
off_t orig_offset = lseek(fd, 0, SEEK_CUR);
if (orig_offset == (off_t)-1) return -1;
if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) return -1;
ssize_t len = read(fd, buf, count);
if (len < 0) return len;
if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) return -1;
return len;
}
#endif // !HAVE_PREAD
#ifndef HAVE_PWRITE
static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) {
off_t orig_offset = lseek(fd, 0, SEEK_CUR);
if (orig_offset == (off_t)-1) return -1;
if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) return -1;
ssize_t len = write(fd, buf, count);
if (len < 0) return len;
if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) return -1;
return len;
}
#endif // !HAVE_PWRITE
static void GetHostName(string* hostname) {
#if defined(HAVE_SYS_UTSNAME_H)
struct utsname buf;
if (uname(&buf) < 0) {
// ensure null termination on failure
*buf.nodename = '\0';
}
*hostname = buf.nodename;
#elif defined(GLOG_OS_WINDOWS)
char buf[MAX_COMPUTERNAME_LENGTH + 1];
DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
if (GetComputerNameA(buf, &len)) {
*hostname = buf;
} else {
hostname->clear();
}
#else
# warning There is no way to retrieve the host name.
*hostname = "(unknown)";
#endif
}
// Returns true iff terminal supports using colors in output.
static bool TerminalSupportsColor() {
bool term_supports_color = false;
#ifdef GLOG_OS_WINDOWS
// on Windows TERM variable is usually not set, but the console does
// support colors.
term_supports_color = true;
#else
// On non-Windows platforms, we rely on the TERM variable.
const char* const term = getenv("TERM");
if (term != nullptr && term[0] != '\0') {
term_supports_color =
!strcmp(term, "xterm") || !strcmp(term, "xterm-color") ||
!strcmp(term, "xterm-256color") || !strcmp(term, "screen-256color") ||
!strcmp(term, "konsole") || !strcmp(term, "konsole-16color") ||
!strcmp(term, "konsole-256color") || !strcmp(term, "screen") ||
!strcmp(term, "linux") || !strcmp(term, "cygwin");
}
#endif
return term_supports_color;
}
#if defined(__cpp_lib_unreachable) && (__cpp_lib_unreachable >= 202202L)
# define GLOG_UNREACHABLE std::unreachable()
#elif !defined(NDEBUG)
# define GLOG_UNREACHABLE assert(false)
#else
# if defined(_MSC_VER)
# define GLOG_UNREACHABLE __assume(false)
# elif defined(__has_builtin)
# if __has_builtin(unreachable)
# define GLOG_UNREACHABLE __builtin_unreachable()
# endif
# endif
# if !defined(GLOG_UNREACHABLE) && defined(__GNUG__)
# define GLOG_UNREACHABLE __builtin_unreachable()
# endif
# if !defined(GLOG_UNREACHABLE)
# define GLOG_UNREACHABLE
# endif
#endif
namespace google {
GLOG_NO_EXPORT
std::string StrError(int err);
enum GLogColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW };
static GLogColor SeverityToColor(LogSeverity severity) {
switch (severity) {
case GLOG_INFO:
return COLOR_DEFAULT;
case GLOG_WARNING:
return COLOR_YELLOW;
case GLOG_ERROR:
case GLOG_FATAL:
return COLOR_RED;
}
// should never get here.
GLOG_UNREACHABLE;
}
#ifdef GLOG_OS_WINDOWS
// Returns the character attribute for the given color.
static WORD GetColorAttribute(GLogColor color) {
switch (color) {
case COLOR_RED:
return FOREGROUND_RED;
case COLOR_GREEN:
return FOREGROUND_GREEN;
case COLOR_YELLOW:
return FOREGROUND_RED | FOREGROUND_GREEN;
case COLOR_DEFAULT:
break;
}
return 0;
}
#else
// Returns the ANSI color code for the given color.
static const char* GetAnsiColorCode(GLogColor color) {
switch (color) {
case COLOR_RED:
return "1";
case COLOR_GREEN:
return "2";
case COLOR_YELLOW:
return "3";
case COLOR_DEFAULT:
return "";
};
return nullptr; // stop warning about return type.
}
#endif // GLOG_OS_WINDOWS
// Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
static uint32 MaxLogSize() {
return (FLAGS_max_log_size > 0 && FLAGS_max_log_size < 4096
? FLAGS_max_log_size
: 1);
}
// An arbitrary limit on the length of a single log message. This
// is so that streaming can be done more efficiently.
const size_t LogMessage::kMaxLogMessageLen = 30000;
namespace logging {
namespace internal {
struct LogMessageData {
LogMessageData();
int preserved_errno_; // preserved errno
// Buffer space; contains complete message text.
char message_text_[LogMessage::kMaxLogMessageLen + 1];
LogMessage::LogStream stream_;
LogSeverity severity_; // What level is this LogMessage logged at?
int line_; // line number where logging call is.
void (LogMessage::*send_method_)(); // Call this in destructor to send
union { // At most one of these is used: union to keep the size low.
LogSink* sink_; // nullptr or sink to send message to
std::vector<std::string>*
outvec_; // nullptr or vector to push message onto
std::string* message_; // nullptr or string to write message into
};
size_t num_prefix_chars_; // # of chars of prefix in this message
size_t num_chars_to_log_; // # of chars of msg to send to log
size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
const char* basename_; // basename of file that called LOG
const char* fullname_; // fullname of file that called LOG
bool has_been_flushed_; // false => data has not been flushed
bool first_fatal_; // true => this was first fatal msg
std::thread::id thread_id_;
LogMessageData(const LogMessageData&) = delete;
LogMessageData& operator=(const LogMessageData&) = delete;
};
} // namespace internal
} // namespace logging
// A mutex that allows only one thread to log at a time, to keep things from
// getting jumbled. Some other very uncommon logging operations (like
// changing the destination file for log messages of a given severity) also
// lock this mutex. Please be sure that anybody who might possibly need to
// lock it does so.
static std::mutex log_mutex;
// Number of messages sent at each severity. Under log_mutex.
int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
// Globally disable log writing (if disk is full)
static bool stop_writing = false;
const char* const LogSeverityNames[] = {"INFO", "WARNING", "ERROR", "FATAL"};
// Has the user called SetExitOnDFatal(true)?
static bool exit_on_dfatal = true;
const char* GetLogSeverityName(LogSeverity severity) {
return LogSeverityNames[severity];
}
static bool SendEmailInternal(const char* dest, const char* subject,
const char* body, bool use_logging);
base::Logger::~Logger() = default;
namespace {
constexpr std::intmax_t kSecondsInDay = 60 * 60 * 24;
constexpr std::intmax_t kSecondsInWeek = kSecondsInDay * 7;
// Optional user-configured callback to print custom prefixes.
class PrefixFormatter {
public:
PrefixFormatter(PrefixFormatterCallback callback, void* data) noexcept
: version{V2}, callback_v2{callback}, data{data} {}
void operator()(std::ostream& s, const LogMessage& message) const {
switch (version) {
case V2:
callback_v2(s, message, data);
break;
}
}
PrefixFormatter(const PrefixFormatter& other) = delete;
PrefixFormatter& operator=(const PrefixFormatter& other) = delete;
private:
enum Version { V2 } version;
union {
PrefixFormatterCallback callback_v2;
};
// User-provided data to pass to the callback:
void* data;
};
std::unique_ptr<PrefixFormatter> g_prefix_formatter;
// Encapsulates all file-system related state
class LogFileObject : public base::Logger {
public:
LogFileObject(LogSeverity severity, const char* base_filename);
~LogFileObject() override;
void Write(bool force_flush, // Should we force a flush here?
const std::chrono::system_clock::time_point&
timestamp, // Timestamp for this entry
const char* message, size_t message_len) override;
// Configuration options
void SetBasename(const char* basename);
void SetExtension(const char* ext);
void SetSymlinkBasename(const char* symlink_basename);
// Normal flushing routine
void Flush() override;
// It is the actual file length for the system loggers,
// i.e., INFO, ERROR, etc.
uint32 LogSize() override {
std::lock_guard<std::mutex> l{mutex_};
return file_length_;
}
// Internal flush routine. Exposed so that FlushLogFilesUnsafe()
// can avoid grabbing a lock. Usually Flush() calls it after
// acquiring lock_.
void FlushUnlocked(const std::chrono::system_clock::time_point& now);
private:
static const uint32 kRolloverAttemptFrequency = 0x20;
std::mutex mutex_;
bool base_filename_selected_;
string base_filename_;
string symlink_basename_;
string filename_extension_; // option users can specify (eg to add port#)
std::unique_ptr<FILE> file_;
LogSeverity severity_;
uint32 bytes_since_flush_{0};
uint32 dropped_mem_length_{0};
uint32 file_length_{0};
unsigned int rollover_attempt_;
std::chrono::system_clock::time_point
next_flush_time_; // cycle count at which to flush log
std::chrono::system_clock::time_point start_time_;
// Actually create a logfile using the value of base_filename_ and the
// optional argument time_pid_string
// REQUIRES: lock_ is held
bool CreateLogfile(const string& time_pid_string);
};
// Encapsulate all log cleaner related states
class LogCleaner {
public:
LogCleaner();
// Setting overdue to 0 days will delete all logs.
void Enable(const std::chrono::minutes& overdue);
void Disable();
void Run(const std::chrono::system_clock::time_point& current_time,
bool base_filename_selected, const string& base_filename,
const string& filename_extension);
bool enabled() const { return enabled_; }
private:
vector<string> GetOverdueLogNames(
string log_directory,
const std::chrono::system_clock::time_point& current_time,
const string& base_filename, const string& filename_extension) const;
bool IsLogFromCurrentProject(const string& filepath,
const string& base_filename,
const string& filename_extension) const;
bool IsLogLastModifiedOver(
const string& filepath,
const std::chrono::system_clock::time_point& current_time) const;
bool enabled_{false};
std::chrono::minutes overdue_{
std::chrono::duration<int, std::ratio<kSecondsInWeek>>{1}};
std::chrono::system_clock::time_point
next_cleanup_time_; // cycle count at which to clean overdue log
};
LogCleaner log_cleaner;
} // namespace
class LogDestination {
public:
friend class LogMessage;
friend void ReprintFatalMessage();
friend base::Logger* base::GetLogger(LogSeverity);
friend void base::SetLogger(LogSeverity, base::Logger*);
// These methods are just forwarded to by their global versions.
static void SetLogDestination(LogSeverity severity,
const char* base_filename);
static void SetLogSymlink(LogSeverity severity, const char* symlink_basename);
static void AddLogSink(LogSink* destination);
static void RemoveLogSink(LogSink* destination);
static void SetLogFilenameExtension(const char* filename_extension);
static void SetStderrLogging(LogSeverity min_severity);
static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
static void LogToStderr();
// Flush all log files that are at least at the given severity level
static void FlushLogFiles(int min_severity);
static void FlushLogFilesUnsafe(int min_severity);
// we set the maximum size of our packet to be 1400, the logic being
// to prevent fragmentation.
// Really this number is arbitrary.
static const int kNetworkBytes = 1400;
static const string& hostname();
static const bool& terminal_supports_color() {
return terminal_supports_color_;
}
static void DeleteLogDestinations();
LogDestination(LogSeverity severity, const char* base_filename);
private:
#if defined(__cpp_lib_shared_mutex) && (__cpp_lib_shared_mutex >= 201505L)
// Use untimed shared mutex
using SinkMutex = std::shared_mutex;
using SinkLock = std::lock_guard<SinkMutex>;
#else // !(defined(__cpp_lib_shared_mutex) && (__cpp_lib_shared_mutex >=
// 201505L)) Fallback to timed shared mutex
using SinkMutex = std::shared_timed_mutex;
using SinkLock = std::unique_lock<SinkMutex>;
#endif // defined(__cpp_lib_shared_mutex) && (__cpp_lib_shared_mutex >=
// 201505L)
friend std::default_delete<LogDestination>;
~LogDestination();
// Take a log message of a particular severity and log it to stderr
// iff it's of a high enough severity to deserve it.
static void MaybeLogToStderr(LogSeverity severity, const char* message,
size_t message_len, size_t prefix_len);
// Take a log message of a particular severity and log it to email
// iff it's of a high enough severity to deserve it.
static void MaybeLogToEmail(LogSeverity severity, const char* message,
size_t len);
// Take a log message of a particular severity and log it to a file
// iff the base filename is not "" (which means "don't log to me")
static void MaybeLogToLogfile(
LogSeverity severity,
const std::chrono::system_clock::time_point& timestamp,
const char* message, size_t len);
// Take a log message of a particular severity and log it to the file
// for that severity and also for all files with severity less than
// this severity.
static void LogToAllLogfiles(
LogSeverity severity,
const std::chrono::system_clock::time_point& timestamp,
const char* message, size_t len);
// Send logging info to all registered sinks.
static void LogToSinks(LogSeverity severity, const char* full_filename,
const char* base_filename, int line,
const LogMessageTime& time, const char* message,
size_t message_len);
// Wait for all registered sinks via WaitTillSent
// including the optional one in "data".
static void WaitForSinks(logging::internal::LogMessageData* data);
static LogDestination* log_destination(LogSeverity severity);
base::Logger* GetLoggerImpl() const { return logger_; }
void SetLoggerImpl(base::Logger* logger);
void ResetLoggerImpl() { SetLoggerImpl(&fileobject_); }
LogFileObject fileobject_;
base::Logger* logger_; // Either &fileobject_, or wrapper around it
static std::unique_ptr<LogDestination> log_destinations_[NUM_SEVERITIES];
static std::underlying_type_t<LogSeverity> email_logging_severity_;
static string addresses_;
static string hostname_;
static bool terminal_supports_color_;
// arbitrary global logging destinations.
static std::unique_ptr<vector<LogSink*>> sinks_;
// Protects the vector sinks_,
// but not the LogSink objects its elements reference.
static SinkMutex sink_mutex_;
// Disallow
LogDestination(const LogDestination&) = delete;
LogDestination& operator=(const LogDestination&) = delete;
};
// Errors do not get logged to email by default.
std::underlying_type_t<LogSeverity> LogDestination::email_logging_severity_ =
99999;
string LogDestination::addresses_;
string LogDestination::hostname_;
std::unique_ptr<vector<LogSink*>> LogDestination::sinks_;
LogDestination::SinkMutex LogDestination::sink_mutex_;
bool LogDestination::terminal_supports_color_ = TerminalSupportsColor();
/* static */
const string& LogDestination::hostname() {
if (hostname_.empty()) {
GetHostName(&hostname_);
if (hostname_.empty()) {
hostname_ = "(unknown)";
}
}
return hostname_;
}
LogDestination::LogDestination(LogSeverity severity, const char* base_filename)
: fileobject_(severity, base_filename), logger_(&fileobject_) {}
LogDestination::~LogDestination() { ResetLoggerImpl(); }
void LogDestination::SetLoggerImpl(base::Logger* logger) {
if (logger_ == logger) {
// Prevent releasing currently held sink on reset
return;
}
if (logger_ && logger_ != &fileobject_) {
// Delete user-specified logger set via SetLogger().
delete logger_;
}
logger_ = logger;
}
inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
// assume we have the log_mutex or we simply don't care
// about it
std::for_each(std::next(std::begin(log_destinations_), min_severity),
std::end(log_destinations_),
[now = std::chrono::system_clock::now()](
std::unique_ptr<LogDestination>& log) {
if (log != nullptr) {
// Flush the base fileobject_ logger directly instead of
// going through any wrappers to reduce chance of deadlock.
log->fileobject_.FlushUnlocked(now);
}
});
}
inline void LogDestination::FlushLogFiles(int min_severity) {
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
std::lock_guard<std::mutex> l{log_mutex};
for (int i = min_severity; i < NUM_SEVERITIES; i++) {
LogDestination* log = log_destination(static_cast<LogSeverity>(i));
if (log != nullptr) {
log->logger_->Flush();
}
}
}
inline void LogDestination::SetLogDestination(LogSeverity severity,
const char* base_filename) {
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
std::lock_guard<std::mutex> l{log_mutex};
log_destination(severity)->fileobject_.SetBasename(base_filename);
}
inline void LogDestination::SetLogSymlink(LogSeverity severity,
const char* symlink_basename) {
CHECK_GE(severity, 0);
CHECK_LT(severity, NUM_SEVERITIES);
std::lock_guard<std::mutex> l{log_mutex};
log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
}
inline void LogDestination::AddLogSink(LogSink* destination) {
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
SinkLock l{sink_mutex_};
if (sinks_ == nullptr) sinks_ = std::make_unique<std::vector<LogSink*>>();
sinks_->push_back(destination);
}
inline void LogDestination::RemoveLogSink(LogSink* destination) {
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
SinkLock l{sink_mutex_};
// This doesn't keep the sinks in order, but who cares?
if (sinks_) {
sinks_->erase(std::remove(sinks_->begin(), sinks_->end(), destination),
sinks_->end());
}
}
inline void LogDestination::SetLogFilenameExtension(const char* ext) {
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
std::lock_guard<std::mutex> l{log_mutex};
for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
log_destination(static_cast<LogSeverity>(severity))
->fileobject_.SetExtension(ext);
}
}
inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
std::lock_guard<std::mutex> l{log_mutex};
FLAGS_stderrthreshold = min_severity;
}
inline void LogDestination::LogToStderr() {
// *Don't* put this stuff in a mutex lock, since SetStderrLogging &
// SetLogDestination already do the locking!
SetStderrLogging(GLOG_INFO); // thus everything is "also" logged to stderr
for (int i = 0; i < NUM_SEVERITIES; ++i) {
SetLogDestination(static_cast<LogSeverity>(i),
""); // "" turns off logging to a logfile
}
}
inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
const char* addresses) {
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
std::lock_guard<std::mutex> l{log_mutex};
LogDestination::email_logging_severity_ = min_severity;
LogDestination::addresses_ = addresses;
}
static void ColoredWriteToStderrOrStdout(FILE* output, LogSeverity severity,
const char* message, size_t len) {
bool is_stdout = (output == stdout);
const GLogColor color = (LogDestination::terminal_supports_color() &&
((!is_stdout && FLAGS_colorlogtostderr) ||
(is_stdout && FLAGS_colorlogtostdout)))
? SeverityToColor(severity)
: COLOR_DEFAULT;
// Avoid using cerr from this module since we may get called during
// exit code, and cerr may be partially or fully destroyed by then.
if (COLOR_DEFAULT == color) {
fwrite(message, len, 1, output);
return;
}
#ifdef GLOG_OS_WINDOWS
const HANDLE output_handle =
GetStdHandle(is_stdout ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
// Gets the current text color.
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(output_handle, &buffer_info);
const WORD old_color_attrs = buffer_info.wAttributes;
// We need to flush the stream buffers into the console before each
// SetConsoleTextAttribute call lest it affect the text that is already
// printed but has not yet reached the console.
fflush(output);
SetConsoleTextAttribute(output_handle,
GetColorAttribute(color) | FOREGROUND_INTENSITY);
fwrite(message, len, 1, output);
fflush(output);
// Restores the text color.
SetConsoleTextAttribute(output_handle, old_color_attrs);
#else
fprintf(output, "\033[0;3%sm", GetAnsiColorCode(color));
fwrite(message, len, 1, output);
fprintf(output, "\033[m"); // Resets the terminal to default.
#endif // GLOG_OS_WINDOWS
}
static void ColoredWriteToStdout(LogSeverity severity, const char* message,
size_t len) {
FILE* output = stdout;
// We also need to send logs to the stderr when the severity is
// higher or equal to the stderr threshold.
if (severity >= FLAGS_stderrthreshold) {
output = stderr;
}
ColoredWriteToStderrOrStdout(output, severity, message, len);
}
static void ColoredWriteToStderr(LogSeverity severity, const char* message,
size_t len) {
ColoredWriteToStderrOrStdout(stderr, severity, message, len);
}
static void WriteToStderr(const char* message, size_t len) {
// Avoid using cerr from this module since we may get called during
// exit code, and cerr may be partially or fully destroyed by then.
fwrite(message, len, 1, stderr);
}
inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
const char* message,
size_t message_len,
size_t prefix_len) {
if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
ColoredWriteToStderr(severity, message, message_len);
AlsoErrorWrite(severity,
glog_internal_namespace_::ProgramInvocationShortName(),
message + prefix_len);
}
}
inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
const char* message, size_t len) {
if (severity >= email_logging_severity_ || severity >= FLAGS_logemaillevel) {
string to(FLAGS_alsologtoemail);
if (!addresses_.empty()) {
if (!to.empty()) {
to += ",";
}
to += addresses_;
}
const string subject(
string("[LOG] ") + LogSeverityNames[severity] + ": " +
glog_internal_namespace_::ProgramInvocationShortName());
string body(hostname());
body += "\n\n";
body.append(message, len);
// should NOT use SendEmail(). The caller of this function holds the
// log_mutex and SendEmail() calls LOG/VLOG which will block trying to
// acquire the log_mutex object. Use SendEmailInternal() and set
// use_logging to false.
SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
}
}
inline void LogDestination::MaybeLogToLogfile(
LogSeverity severity,
const std::chrono::system_clock::time_point& timestamp, const char* message,
size_t len) {
const bool should_flush = severity > FLAGS_logbuflevel;
LogDestination* destination = log_destination(severity);
destination->logger_->Write(should_flush, timestamp, message, len);
}
inline void LogDestination::LogToAllLogfiles(
LogSeverity severity,
const std::chrono::system_clock::time_point& timestamp, const char* message,
size_t len) {
if (FLAGS_logtostdout) { // global flag: never log to file
ColoredWriteToStdout(severity, message, len);
} else if (FLAGS_logtostderr) { // global flag: never log to file
ColoredWriteToStderr(severity, message, len);
} else {
for (int i = severity; i >= 0; --i) {
LogDestination::MaybeLogToLogfile(static_cast<LogSeverity>(i), timestamp,
message, len);
}
}
}
inline void LogDestination::LogToSinks(LogSeverity severity,
const char* full_filename,
const char* base_filename, int line,
const LogMessageTime& time,
const char* message,
size_t message_len) {
std::shared_lock<SinkMutex> l{sink_mutex_};
if (sinks_) {
for (size_t i = sinks_->size(); i-- > 0;) {
(*sinks_)[i]->send(severity, full_filename, base_filename, line, time,
message, message_len);
}
}
}
inline void LogDestination::WaitForSinks(
logging::internal::LogMessageData* data) {
std::shared_lock<SinkMutex> l{sink_mutex_};
if (sinks_) {
for (size_t i = sinks_->size(); i-- > 0;) {
(*sinks_)[i]->WaitTillSent();
}
}
const bool send_to_sink =
(data->send_method_ == &LogMessage::SendToSink) ||
(data->send_method_ == &LogMessage::SendToSinkAndLog);
if (send_to_sink && data->sink_ != nullptr) {
data->sink_->WaitTillSent();
}
}
std::unique_ptr<LogDestination>
LogDestination::log_destinations_[NUM_SEVERITIES];
inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
if (log_destinations_[severity] == nullptr) {
log_destinations_[severity] =
std::make_unique<LogDestination>(severity, nullptr);
}
return log_destinations_[severity].get();
}
void LogDestination::DeleteLogDestinations() {
for (auto& log_destination : log_destinations_) {
log_destination.reset();
}
SinkLock l{sink_mutex_};
sinks_.reset();
}
namespace {
std::string g_application_fingerprint;
} // namespace
void SetApplicationFingerprint(const std::string& fingerprint) {
g_application_fingerprint = fingerprint;
}
namespace {
// Directory delimiter; Windows supports both forward slashes and backslashes
#ifdef GLOG_OS_WINDOWS
const char possible_dir_delim[] = {'\\', '/'};
#else
const char possible_dir_delim[] = {'/'};
#endif
string PrettyDuration(const std::chrono::duration<int>& secs) {
std::stringstream result;
int mins = secs.count() / 60;
int hours = mins / 60;
mins = mins % 60;
int s = secs.count() % 60;
result.fill('0');
result << hours << ':' << setw(2) << mins << ':' << setw(2) << s;
return result.str();
}
LogFileObject::LogFileObject(LogSeverity severity, const char* base_filename)
: base_filename_selected_(base_filename != nullptr),
base_filename_((base_filename != nullptr) ? base_filename : ""),
symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
filename_extension_(),
severity_(severity),
rollover_attempt_(kRolloverAttemptFrequency - 1),
start_time_(std::chrono::system_clock::now()) {}
LogFileObject::~LogFileObject() {
std::lock_guard<std::mutex> l{mutex_};
file_ = nullptr;
}
void LogFileObject::SetBasename(const char* basename) {
std::lock_guard<std::mutex> l{mutex_};
base_filename_selected_ = true;
if (base_filename_ != basename) {
// Get rid of old log file since we are changing names
if (file_ != nullptr) {
file_ = nullptr;
rollover_attempt_ = kRolloverAttemptFrequency - 1;
}
base_filename_ = basename;
}
}
void LogFileObject::SetExtension(const char* ext) {
std::lock_guard<std::mutex> l{mutex_};
if (filename_extension_ != ext) {
// Get rid of old log file since we are changing names
if (file_ != nullptr) {
file_ = nullptr;
rollover_attempt_ = kRolloverAttemptFrequency - 1;
}
filename_extension_ = ext;
}
}
void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
std::lock_guard<std::mutex> l{mutex_};
symlink_basename_ = symlink_basename;
}
void LogFileObject::Flush() {
std::lock_guard<std::mutex> l{mutex_};
FlushUnlocked(std::chrono::system_clock::now());
}
void LogFileObject::FlushUnlocked(
const std::chrono::system_clock::time_point& now) {
if (file_ != nullptr) {
fflush(file_.get());
bytes_since_flush_ = 0;
}
// Figure out when we are due for another flush.
next_flush_time_ =
now + std::chrono::duration_cast<std::chrono::system_clock::duration>(
std::chrono::duration<int32>{FLAGS_logbufsecs});
}
bool LogFileObject::CreateLogfile(const string& time_pid_string) {
string string_filename = base_filename_;
if (FLAGS_timestamp_in_logfile_name) {
string_filename += time_pid_string;
}
string_filename += filename_extension_;
const char* filename = string_filename.c_str();
// only write to files, create if non-existant.
int flags = O_WRONLY | O_CREAT;
if (FLAGS_timestamp_in_logfile_name) {
// demand that the file is unique for our timestamp (fail if it exists).
flags = flags | O_EXCL;
}
FileDescriptor fd{
open(filename, flags, static_cast<mode_t>(FLAGS_logfile_mode))};