-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
logging.cc
2528 lines (2205 loc) · 83 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) 1999, 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 "utilities.h"
#include <algorithm>
#include <cassert>
#include <iomanip>
#include <string>
#ifdef HAVE_UNISTD_H
# include <unistd.h> // For _exit.
#endif
#include <climits>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_UTSNAME_H
# include <sys/utsname.h> // For uname.
#endif
#include <ctime>
#include <fcntl.h>
#include <cstdio>
#include <iostream>
#include <cstdarg>
#include <cstdlib>
#ifdef HAVE_PWD_H
# include <pwd.h>
#endif
#ifdef HAVE_SYSLOG_H
# include <syslog.h>
#endif
#include <vector>
#include <cerrno> // for errno
#include <sstream>
#ifdef OS_WINDOWS
#include "windows/dirent.h"
#else
#include <dirent.h> // for automatic removal of old logs
#endif
#include "base/commandlineflags.h" // to get the program name
#include "glog/logging.h"
#include "glog/raw_logging.h"
#include "base/googleinit.h"
#ifdef HAVE_STACKTRACE
# include "stacktrace.h"
#endif
#ifdef __ANDROID__
#include <android/log.h>
#endif
using std::string;
using std::vector;
using std::setw;
using std::setfill;
using std::hex;
using std::dec;
using std::min;
using std::ostream;
using std::ostringstream;
using std::FILE;
using std::fwrite;
using std::fclose;
using std::fflush;
using std::fprintf;
using std::perror;
#ifdef __QNX__
using std::fdopen;
#endif
#ifdef _WIN32
#define fdopen _fdopen
#endif
// There is no thread annotation support.
#define EXCLUSIVE_LOCKS_REQUIRED(mu)
static bool BoolFromEnv(const char *varname, bool defval) {
const char* const valstr = getenv(varname);
if (!valstr) {
return defval;
}
return memchr("tTyY1\0", valstr[0], 6) != NULL;
}
GLOG_DEFINE_bool(timestamp_in_logfile_name,
BoolFromEnv("GOOGLE_TIMESTAMP_IN_LOGFILE_NAME", true),
"put a timestamp at the end of the log file name");
GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
"log messages go to stderr instead of logfiles");
GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
"log messages go to stderr in addition to logfiles");
GLOG_DEFINE_bool(colorlogtostderr, false,
"color messages logged to stderr (if supported by terminal)");
#ifdef OS_LINUX
GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
"Logs can grow very quickly and they are rarely read before they "
"need to be evicted from memory. Instead, drop them from memory "
"as soon as they are flushed to disk.");
#endif
// By default, errors (including fatal errors) get logged to stderr as
// well as the file.
//
// The default is ERROR instead of FATAL so that users can see problems
// when they run a program without having to look in another file.
DEFINE_int32(stderrthreshold,
GOOGLE_NAMESPACE::GLOG_ERROR,
"log messages at or above this level are copied to stderr in "
"addition to logfiles. This flag obsoletes --alsologtostderr.");
GLOG_DEFINE_string(alsologtoemail, "",
"log messages go to these email addresses "
"in addition to logfiles");
GLOG_DEFINE_bool(log_prefix, true,
"Prepend the log prefix to the start of each log line");
GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
"actually get logged anywhere");
GLOG_DEFINE_int32(logbuflevel, 0,
"Buffer log messages logged at this level or lower"
" (-1 means don't buffer; 0 means buffer INFO only;"
" ...)");
GLOG_DEFINE_int32(logbufsecs, 30,
"Buffer log messages for at most this many seconds");
GLOG_DEFINE_int32(logemaillevel, 999,
"Email log messages logged at this level or higher"
" (0 means email all; 3 means email FATAL only;"
" ...)");
GLOG_DEFINE_string(logmailer, "",
"Mailer used to send logging email");
// Compute the default value for --log_dir
static const char* DefaultLogDir() {
const char* env;
env = getenv("GOOGLE_LOG_DIR");
if (env != NULL && env[0] != '\0') {
return env;
}
env = getenv("TEST_TMPDIR");
if (env != NULL && env[0] != '\0') {
return env;
}
return "";
}
GLOG_DEFINE_int32(logfile_mode, 0664, "Log file mode/permissions.");
GLOG_DEFINE_string(log_dir, DefaultLogDir(),
"If specified, logfiles are written into this directory instead "
"of the default logging directory.");
GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
"files in this directory");
GLOG_DEFINE_int32(max_log_size, 1800,
"approx. maximum log file size (in MB). A value of 0 will "
"be silently overridden to 1.");
GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
"Stop attempting to log to disk if the disk is full.");
GLOG_DEFINE_string(log_backtrace_at, "",
"Emit a backtrace when logging at file:linenum.");
GLOG_DEFINE_bool(log_utc_time, false,
"Use UTC time for logging.");
// TODO(hamaji): consider windows
#define PATH_SEPARATOR '/'
#ifndef HAVE_PREAD
#if defined(OS_WINDOWS)
#include <basetsd.h>
#define ssize_t SSIZE_T
#endif
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 (0 != uname(&buf)) {
// ensure null termination on failure
*buf.nodename = '\0';
}
*hostname = buf.nodename;
#elif defined(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 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 != NULL && 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;
}
_START_GOOGLE_NAMESPACE_
enum GLogColor {
COLOR_DEFAULT,
COLOR_RED,
COLOR_GREEN,
COLOR_YELLOW
};
static GLogColor SeverityToColor(LogSeverity severity) {
assert(severity >= 0 && severity < NUM_SEVERITIES);
GLogColor color = COLOR_DEFAULT;
switch (severity) {
case GLOG_INFO:
color = COLOR_DEFAULT;
break;
case GLOG_WARNING:
color = COLOR_YELLOW;
break;
case GLOG_ERROR:
case GLOG_FATAL:
color = COLOR_RED;
break;
default:
// should never get here.
assert(false);
}
return color;
}
#ifdef 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;
default: 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 NULL; // stop warning about return type.
}
#endif // OS_WINDOWS
// Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
static int32 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;
struct LogMessage::LogMessageData {
LogMessageData();
int preserved_errno_; // preserved errno
// Buffer space; contains complete message text.
char message_text_[LogMessage::kMaxLogMessageLen+1];
LogStream stream_;
char 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_; // NULL or sink to send message to
std::vector<std::string>* outvec_; // NULL or vector to push message onto
std::string* message_; // NULL or string to write message into
};
time_t timestamp_; // Time of creation of LogMessage
struct ::tm tm_time_; // Time of creation of LogMessage
int32 usecs_; // Time of creation of LogMessage - microseconds part
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
private:
LogMessageData(const LogMessageData&);
void operator=(const LogMessageData&);
};
// 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 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[NUM_SEVERITIES] = {
"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() {
}
namespace {
// Encapsulates all file-system related state
class LogFileObject : public base::Logger {
public:
LogFileObject(LogSeverity severity, const char* base_filename);
~LogFileObject();
virtual void Write(bool force_flush, // Should we force a flush here?
time_t timestamp, // Timestamp for this entry
const char* message,
int message_len);
// Configuration options
void SetBasename(const char* basename);
void SetExtension(const char* ext);
void SetSymlinkBasename(const char* symlink_basename);
// Normal flushing routine
virtual void Flush();
// It is the actual file length for the system loggers,
// i.e., INFO, ERROR, etc.
virtual uint32 LogSize() {
MutexLock l(&lock_);
return file_length_;
}
// Internal flush routine. Exposed so that FlushLogFilesUnsafe()
// can avoid grabbing a lock. Usually Flush() calls it after
// acquiring lock_.
void FlushUnlocked();
private:
static const uint32 kRolloverAttemptFrequency = 0x20;
Mutex lock_;
bool base_filename_selected_;
string base_filename_;
string symlink_basename_;
string filename_extension_; // option users can specify (eg to add port#)
FILE* file_;
LogSeverity severity_;
uint32 bytes_since_flush_;
uint32 dropped_mem_length_;
uint32 file_length_;
unsigned int rollover_attempt_;
int64 next_flush_time_; // cycle count at which to flush log
WallTime 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();
virtual ~LogCleaner() {}
void Enable(int overdue_days);
void Disable();
void Run(bool base_filename_selected,
const string& base_filename,
const string& filename_extension) const;
inline bool enabled() const { return enabled_; }
private:
vector<string> GetOverdueLogNames(string log_directory,
int days,
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, int days) const;
bool enabled_;
int overdue_days_;
char dir_delim_; // filepath delimiter ('/' or '\\')
};
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();
private:
LogDestination(LogSeverity severity, const char* base_filename);
~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,
time_t 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,
time_t 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 struct ::tm* tm_time,
const char* message,
size_t message_len,
int32 usecs);
// Wait for all registered sinks via WaitTillSent
// including the optional one in "data".
static void WaitForSinks(LogMessage::LogMessageData* data);
static LogDestination* log_destination(LogSeverity severity);
LogFileObject fileobject_;
base::Logger* logger_; // Either &fileobject_, or wrapper around it
static LogDestination* log_destinations_[NUM_SEVERITIES];
static LogSeverity email_logging_severity_;
static string addresses_;
static string hostname_;
static bool terminal_supports_color_;
// arbitrary global logging destinations.
static vector<LogSink*>* sinks_;
// Protects the vector sinks_,
// but not the LogSink objects its elements reference.
static Mutex sink_mutex_;
// Disallow
LogDestination(const LogDestination&);
LogDestination& operator=(const LogDestination&);
};
// Errors do not get logged to email by default.
LogSeverity LogDestination::email_logging_severity_ = 99999;
string LogDestination::addresses_;
string LogDestination::hostname_;
vector<LogSink*>* LogDestination::sinks_ = NULL;
Mutex 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() {
if (logger_ && logger_ != &fileobject_) {
// Delete user-specified logger set via SetLogger().
delete logger_;
}
}
inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
// assume we have the log_mutex or we simply don't care
// about it
for (int i = min_severity; i < NUM_SEVERITIES; i++) {
LogDestination* log = log_destinations_[i];
if (log != NULL) {
// Flush the base fileobject_ logger directly instead of going
// through any wrappers to reduce chance of deadlock.
log->fileobject_.FlushUnlocked();
}
}
}
inline void LogDestination::FlushLogFiles(int min_severity) {
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
MutexLock l(&log_mutex);
for (int i = min_severity; i < NUM_SEVERITIES; i++) {
LogDestination* log = log_destination(i);
if (log != NULL) {
log->logger_->Flush();
}
}
}
inline void LogDestination::SetLogDestination(LogSeverity severity,
const char* base_filename) {
assert(severity >= 0 && severity < NUM_SEVERITIES);
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
MutexLock 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);
MutexLock 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.
MutexLock l(&sink_mutex_);
if (!sinks_) sinks_ = new 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.
MutexLock l(&sink_mutex_);
// This doesn't keep the sinks in order, but who cares?
if (sinks_) {
for (int i = sinks_->size() - 1; i >= 0; i--) {
if ((*sinks_)[i] == destination) {
(*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
sinks_->pop_back();
break;
}
}
}
}
inline void LogDestination::SetLogFilenameExtension(const char* ext) {
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
MutexLock l(&log_mutex);
for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
log_destination(severity)->fileobject_.SetExtension(ext);
}
}
inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
MutexLock 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(0); // thus everything is "also" logged to stderr
for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
SetLogDestination(i, ""); // "" turns off logging to a logfile
}
}
inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
const char* addresses) {
assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
// Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff.
MutexLock l(&log_mutex);
LogDestination::email_logging_severity_ = min_severity;
LogDestination::addresses_ = addresses;
}
static void ColoredWriteToStderr(LogSeverity severity,
const char* message, size_t len) {
const GLogColor color =
(LogDestination::terminal_supports_color() && FLAGS_colorlogtostderr) ?
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, stderr);
return;
}
#ifdef OS_WINDOWS
const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
// Gets the current text color.
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(stderr_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(stderr);
SetConsoleTextAttribute(stderr_handle,
GetColorAttribute(color) | FOREGROUND_INTENSITY);
fwrite(message, len, 1, stderr);
fflush(stderr);
// Restores the text color.
SetConsoleTextAttribute(stderr_handle, old_color_attrs);
#else
fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color));
fwrite(message, len, 1, stderr);
fprintf(stderr, "\033[m"); // Resets the terminal to default.
#endif // OS_WINDOWS
}
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);
#ifdef OS_WINDOWS
// On Windows, also output to the debugger
::OutputDebugStringA(message);
#elif defined(__ANDROID__)
// On Android, also output to logcat
const int android_log_levels[NUM_SEVERITIES] = {
ANDROID_LOG_INFO,
ANDROID_LOG_WARN,
ANDROID_LOG_ERROR,
ANDROID_LOG_FATAL,
};
__android_log_write(android_log_levels[severity],
glog_internal_namespace_::ProgramInvocationShortName(),
message + prefix_len);
#endif
}
}
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,
time_t 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,
time_t timestamp,
const char* message,
size_t len) {
if ( FLAGS_logtostderr ) { // global flag: never log to file
ColoredWriteToStderr(severity, message, len);
} else {
for (int i = severity; i >= 0; --i)
LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
}
}
inline void LogDestination::LogToSinks(LogSeverity severity,
const char *full_filename,
const char *base_filename,
int line,
const struct ::tm* tm_time,
const char* message,
size_t message_len,
int32 usecs) {
ReaderMutexLock l(&sink_mutex_);
if (sinks_) {
for (int i = sinks_->size() - 1; i >= 0; i--) {
(*sinks_)[i]->send(severity, full_filename, base_filename,
line, tm_time, message, message_len, usecs);
}
}
}
inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
ReaderMutexLock l(&sink_mutex_);
if (sinks_) {
for (int i = sinks_->size() - 1; i >= 0; i--) {
(*sinks_)[i]->WaitTillSent();
}
}
const bool send_to_sink =
(data->send_method_ == &LogMessage::SendToSink) ||
(data->send_method_ == &LogMessage::SendToSinkAndLog);
if (send_to_sink && data->sink_ != NULL) {
data->sink_->WaitTillSent();
}
}
LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
assert(severity >=0 && severity < NUM_SEVERITIES);
if (!log_destinations_[severity]) {
log_destinations_[severity] = new LogDestination(severity, NULL);
}
return log_destinations_[severity];
}
void LogDestination::DeleteLogDestinations() {
for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
delete log_destinations_[severity];
log_destinations_[severity] = NULL;
}
MutexLock l(&sink_mutex_);
delete sinks_;
sinks_ = NULL;
}
namespace {
std::string g_application_fingerprint;
} // namespace
void SetApplicationFingerprint(const std::string& fingerprint) {
g_application_fingerprint = fingerprint;
}
namespace {
string PrettyDuration(int secs) {
std::stringstream result;
int mins = secs / 60;
int hours = mins / 60;
mins = mins % 60;
secs = secs % 60;
result.fill('0');
result << hours << ':' << setw(2) << mins << ':' << setw(2) << secs;
return result.str();
}
LogFileObject::LogFileObject(LogSeverity severity,
const char* base_filename)
: base_filename_selected_(base_filename != NULL),
base_filename_((base_filename != NULL) ? base_filename : ""),
symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
filename_extension_(),
file_(NULL),
severity_(severity),
bytes_since_flush_(0),
dropped_mem_length_(0),
file_length_(0),
rollover_attempt_(kRolloverAttemptFrequency-1),
next_flush_time_(0),
start_time_(WallTime_Now()) {
assert(severity >= 0);
assert(severity < NUM_SEVERITIES);
}
LogFileObject::~LogFileObject() {
MutexLock l(&lock_);
if (file_ != NULL) {
fclose(file_);
file_ = NULL;
}
}
void LogFileObject::SetBasename(const char* basename) {
MutexLock l(&lock_);
base_filename_selected_ = true;
if (base_filename_ != basename) {
// Get rid of old log file since we are changing names
if (file_ != NULL) {
fclose(file_);
file_ = NULL;
rollover_attempt_ = kRolloverAttemptFrequency-1;
}
base_filename_ = basename;
}
}
void LogFileObject::SetExtension(const char* ext) {
MutexLock l(&lock_);
if (filename_extension_ != ext) {
// Get rid of old log file since we are changing names
if (file_ != NULL) {
fclose(file_);
file_ = NULL;
rollover_attempt_ = kRolloverAttemptFrequency-1;
}
filename_extension_ = ext;
}
}
void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
MutexLock l(&lock_);
symlink_basename_ = symlink_basename;
}
void LogFileObject::Flush() {
MutexLock l(&lock_);
FlushUnlocked();
}
void LogFileObject::FlushUnlocked(){
if (file_ != NULL) {
fflush(file_);
bytes_since_flush_ = 0;
}
// Figure out when we are due for another flush.
const int64 next = (FLAGS_logbufsecs
* static_cast<int64>(1000000)); // in usec
next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
}
bool LogFileObject::CreateLogfile(const string& time_pid_string) {
string string_filename = base_filename_;