1 // Copyright (c) 1999, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite()
32 #include "utilities.h"
38 # include <unistd.h> // For _exit.
41 #include <sys/types.h>
43 #ifdef HAVE_SYS_UTSNAME_H
44 # include <sys/utsname.h> // For uname.
58 #include <errno.h> // for errno
60 #include "base/commandlineflags.h" // to get the program name
61 #include "glog/logging.h"
62 #include "glog/raw_logging.h"
63 #include "base/googleinit.h"
65 #ifdef HAVE_STACKTRACE
66 # include "stacktrace.h"
77 using std::ostringstream;
90 // There is no thread annotation support.
91 #define EXCLUSIVE_LOCKS_REQUIRED(mu)
93 static bool BoolFromEnv(const char *varname, bool defval) {
94 const char* const valstr = getenv(varname);
98 return memchr("tTyY1\0", valstr[0], 6) != NULL;
101 GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
102 "log messages go to stderr instead of logfiles");
103 GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
104 "log messages go to stderr in addition to logfiles");
105 GLOG_DEFINE_bool(colorlogtostderr, false,
106 "color messages logged to stderr (if supported by terminal)");
108 GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
109 "Logs can grow very quickly and they are rarely read before they "
110 "need to be evicted from memory. Instead, drop them from memory "
111 "as soon as they are flushed to disk.");
112 _START_GOOGLE_NAMESPACE_
114 static const int64 kPageSize = getpagesize();
116 _END_GOOGLE_NAMESPACE_
119 // By default, errors (including fatal errors) get logged to stderr as
122 // The default is ERROR instead of FATAL so that users can see problems
123 // when they run a program without having to look in another file.
124 DEFINE_int32(stderrthreshold,
125 GOOGLE_NAMESPACE::GLOG_ERROR,
126 "log messages at or above this level are copied to stderr in "
127 "addition to logfiles. This flag obsoletes --alsologtostderr.");
129 GLOG_DEFINE_string(alsologtoemail, "",
130 "log messages go to these email addresses "
131 "in addition to logfiles");
132 GLOG_DEFINE_bool(log_prefix, true,
133 "Prepend the log prefix to the start of each log line");
134 GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
135 "actually get logged anywhere");
136 GLOG_DEFINE_int32(logbuflevel, 0,
137 "Buffer log messages logged at this level or lower"
138 " (-1 means don't buffer; 0 means buffer INFO only;"
140 GLOG_DEFINE_int32(logbufsecs, 30,
141 "Buffer log messages for at most this many seconds");
142 GLOG_DEFINE_int32(logemaillevel, 999,
143 "Email log messages logged at this level or higher"
144 " (0 means email all; 3 means email FATAL only;"
146 GLOG_DEFINE_string(logmailer, "/bin/mail",
147 "Mailer used to send logging email");
149 // Compute the default value for --log_dir
150 static const char* DefaultLogDir() {
152 env = getenv("GOOGLE_LOG_DIR");
153 if (env != NULL && env[0] != '\0') {
156 env = getenv("TEST_TMPDIR");
157 if (env != NULL && env[0] != '\0') {
163 GLOG_DEFINE_string(log_dir, DefaultLogDir(),
164 "If specified, logfiles are written into this directory instead "
165 "of the default logging directory.");
166 GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
167 "files in this directory");
169 GLOG_DEFINE_int32(max_log_size, 1800,
170 "approx. maximum log file size (in MB). A value of 0 will "
171 "be silently overridden to 1.");
173 GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
174 "Stop attempting to log to disk if the disk is full.");
176 GLOG_DEFINE_string(log_backtrace_at, "",
177 "Emit a backtrace when logging at file:linenum.");
179 // TODO(hamaji): consider windows
180 #define PATH_SEPARATOR '/'
183 static ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
184 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
185 if (orig_offset == (off_t)-1)
187 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
189 ssize_t len = read(fd, buf, count);
192 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
196 #endif // !HAVE_PREAD
199 static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) {
200 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
201 if (orig_offset == (off_t)-1)
203 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
205 ssize_t len = write(fd, buf, count);
208 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
212 #endif // !HAVE_PWRITE
214 static void GetHostName(string* hostname) {
215 #if defined(HAVE_SYS_UTSNAME_H)
217 if (0 != uname(&buf)) {
218 // ensure null termination on failure
219 *buf.nodename = '\0';
221 *hostname = buf.nodename;
222 #elif defined(OS_WINDOWS)
223 char buf[MAX_COMPUTERNAME_LENGTH + 1];
224 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
225 if (GetComputerNameA(buf, &len)) {
231 # warning There is no way to retrieve the host name.
232 *hostname = "(unknown)";
236 // Returns true iff terminal supports using colors in output.
237 static bool TerminalSupportsColor() {
238 bool term_supports_color = false;
240 // on Windows TERM variable is usually not set, but the console does
242 term_supports_color = true;
244 // On non-Windows platforms, we rely on the TERM variable.
245 const char* const term = getenv("TERM");
246 if (term != NULL && term[0] != '\0') {
247 term_supports_color =
248 !strcmp(term, "xterm") ||
249 !strcmp(term, "xterm-color") ||
250 !strcmp(term, "xterm-256color") ||
251 !strcmp(term, "screen") ||
252 !strcmp(term, "linux") ||
253 !strcmp(term, "cygwin");
256 return term_supports_color;
259 _START_GOOGLE_NAMESPACE_
268 static GLogColor SeverityToColor(LogSeverity severity) {
269 assert(severity >= 0 && severity < NUM_SEVERITIES);
270 GLogColor color = COLOR_DEFAULT;
273 color = COLOR_DEFAULT;
276 color = COLOR_YELLOW;
283 // should never get here.
291 // Returns the character attribute for the given color.
292 WORD GetColorAttribute(GLogColor color) {
294 case COLOR_RED: return FOREGROUND_RED;
295 case COLOR_GREEN: return FOREGROUND_GREEN;
296 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
303 // Returns the ANSI color code for the given color.
304 const char* GetAnsiColorCode(GLogColor color) {
306 case COLOR_RED: return "1";
307 case COLOR_GREEN: return "2";
308 case COLOR_YELLOW: return "3";
309 case COLOR_DEFAULT: return "";
311 return NULL; // stop warning about return type.
316 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
317 static int32 MaxLogSize() {
318 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
321 // An arbitrary limit on the length of a single log message. This
322 // is so that streaming can be done more efficiently.
323 const size_t LogMessage::kMaxLogMessageLen = 30000;
325 struct LogMessage::LogMessageData {
328 int preserved_errno_; // preserved errno
329 // Buffer space; contains complete message text.
330 char message_text_[LogMessage::kMaxLogMessageLen+1];
332 char severity_; // What level is this LogMessage logged at?
333 int line_; // line number where logging call is.
334 void (LogMessage::*send_method_)(); // Call this in destructor to send
335 union { // At most one of these is used: union to keep the size low.
336 LogSink* sink_; // NULL or sink to send message to
337 std::vector<std::string>* outvec_; // NULL or vector to push message onto
338 std::string* message_; // NULL or string to write message into
340 time_t timestamp_; // Time of creation of LogMessage
341 struct ::tm tm_time_; // Time of creation of LogMessage
342 size_t num_prefix_chars_; // # of chars of prefix in this message
343 size_t num_chars_to_log_; // # of chars of msg to send to log
344 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
345 const char* basename_; // basename of file that called LOG
346 const char* fullname_; // fullname of file that called LOG
347 bool has_been_flushed_; // false => data has not been flushed
348 bool first_fatal_; // true => this was first fatal msg
351 LogMessageData(const LogMessageData&);
352 void operator=(const LogMessageData&);
355 // A mutex that allows only one thread to log at a time, to keep things from
356 // getting jumbled. Some other very uncommon logging operations (like
357 // changing the destination file for log messages of a given severity) also
358 // lock this mutex. Please be sure that anybody who might possibly need to
360 static Mutex log_mutex;
362 // Number of messages sent at each severity. Under log_mutex.
363 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
365 // Globally disable log writing (if disk is full)
366 static bool stop_writing = false;
368 const char*const LogSeverityNames[NUM_SEVERITIES] = {
369 "INFO", "WARNING", "ERROR", "FATAL"
372 // Has the user called SetExitOnDFatal(true)?
373 static bool exit_on_dfatal = true;
375 const char* GetLogSeverityName(LogSeverity severity) {
376 return LogSeverityNames[severity];
379 static bool SendEmailInternal(const char*dest, const char *subject,
380 const char*body, bool use_logging);
382 base::Logger::~Logger() {
387 // Encapsulates all file-system related state
388 class LogFileObject : public base::Logger {
390 LogFileObject(LogSeverity severity, const char* base_filename);
393 virtual void Write(bool force_flush, // Should we force a flush here?
394 time_t timestamp, // Timestamp for this entry
398 // Configuration options
399 void SetBasename(const char* basename);
400 void SetExtension(const char* ext);
401 void SetSymlinkBasename(const char* symlink_basename);
403 // Normal flushing routine
404 virtual void Flush();
406 // It is the actual file length for the system loggers,
407 // i.e., INFO, ERROR, etc.
408 virtual uint32 LogSize() {
413 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
414 // can avoid grabbing a lock. Usually Flush() calls it after
416 void FlushUnlocked();
419 static const uint32 kRolloverAttemptFrequency = 0x20;
422 bool base_filename_selected_;
423 string base_filename_;
424 string symlink_basename_;
425 string filename_extension_; // option users can specify (eg to add port#)
427 LogSeverity severity_;
428 uint32 bytes_since_flush_;
430 unsigned int rollover_attempt_;
431 int64 next_flush_time_; // cycle count at which to flush log
433 // Actually create a logfile using the value of base_filename_ and the
434 // supplied argument time_pid_string
435 // REQUIRES: lock_ is held
436 bool CreateLogfile(const string& time_pid_string);
441 class LogDestination {
443 friend class LogMessage;
444 friend void ReprintFatalMessage();
445 friend base::Logger* base::GetLogger(LogSeverity);
446 friend void base::SetLogger(LogSeverity, base::Logger*);
448 // These methods are just forwarded to by their global versions.
449 static void SetLogDestination(LogSeverity severity,
450 const char* base_filename);
451 static void SetLogSymlink(LogSeverity severity,
452 const char* symlink_basename);
453 static void AddLogSink(LogSink *destination);
454 static void RemoveLogSink(LogSink *destination);
455 static void SetLogFilenameExtension(const char* filename_extension);
456 static void SetStderrLogging(LogSeverity min_severity);
457 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
458 static void LogToStderr();
459 // Flush all log files that are at least at the given severity level
460 static void FlushLogFiles(int min_severity);
461 static void FlushLogFilesUnsafe(int min_severity);
463 // we set the maximum size of our packet to be 1400, the logic being
464 // to prevent fragmentation.
465 // Really this number is arbitrary.
466 static const int kNetworkBytes = 1400;
468 static const string& hostname();
469 static const bool& terminal_supports_color() {
470 return terminal_supports_color_;
473 static void DeleteLogDestinations();
476 LogDestination(LogSeverity severity, const char* base_filename);
477 ~LogDestination() { }
479 // Take a log message of a particular severity and log it to stderr
480 // iff it's of a high enough severity to deserve it.
481 static void MaybeLogToStderr(LogSeverity severity, const char* message,
484 // Take a log message of a particular severity and log it to email
485 // iff it's of a high enough severity to deserve it.
486 static void MaybeLogToEmail(LogSeverity severity, const char* message,
488 // Take a log message of a particular severity and log it to a file
489 // iff the base filename is not "" (which means "don't log to me")
490 static void MaybeLogToLogfile(LogSeverity severity,
492 const char* message, size_t len);
493 // Take a log message of a particular severity and log it to the file
494 // for that severity and also for all files with severity less than
496 static void LogToAllLogfiles(LogSeverity severity,
498 const char* message, size_t len);
500 // Send logging info to all registered sinks.
501 static void LogToSinks(LogSeverity severity,
502 const char *full_filename,
503 const char *base_filename,
505 const struct ::tm* tm_time,
509 // Wait for all registered sinks via WaitTillSent
510 // including the optional one in "data".
511 static void WaitForSinks(LogMessage::LogMessageData* data);
513 static LogDestination* log_destination(LogSeverity severity);
515 LogFileObject fileobject_;
516 base::Logger* logger_; // Either &fileobject_, or wrapper around it
518 static LogDestination* log_destinations_[NUM_SEVERITIES];
519 static LogSeverity email_logging_severity_;
520 static string addresses_;
521 static string hostname_;
522 static bool terminal_supports_color_;
524 // arbitrary global logging destinations.
525 static vector<LogSink*>* sinks_;
527 // Protects the vector sinks_,
528 // but not the LogSink objects its elements reference.
529 static Mutex sink_mutex_;
532 LogDestination(const LogDestination&);
533 LogDestination& operator=(const LogDestination&);
536 // Errors do not get logged to email by default.
537 LogSeverity LogDestination::email_logging_severity_ = 99999;
539 string LogDestination::addresses_;
540 string LogDestination::hostname_;
542 vector<LogSink*>* LogDestination::sinks_ = NULL;
543 Mutex LogDestination::sink_mutex_;
544 bool LogDestination::terminal_supports_color_ = TerminalSupportsColor();
547 const string& LogDestination::hostname() {
548 if (hostname_.empty()) {
549 GetHostName(&hostname_);
550 if (hostname_.empty()) {
551 hostname_ = "(unknown)";
557 LogDestination::LogDestination(LogSeverity severity,
558 const char* base_filename)
559 : fileobject_(severity, base_filename),
560 logger_(&fileobject_) {
563 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
564 // assume we have the log_mutex or we simply don't care
566 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
567 LogDestination* log = log_destination(i);
569 // Flush the base fileobject_ logger directly instead of going
570 // through any wrappers to reduce chance of deadlock.
571 log->fileobject_.FlushUnlocked();
576 inline void LogDestination::FlushLogFiles(int min_severity) {
577 // Prevent any subtle race conditions by wrapping a mutex lock around
579 MutexLock l(&log_mutex);
580 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
581 LogDestination* log = log_destination(i);
583 log->logger_->Flush();
588 inline void LogDestination::SetLogDestination(LogSeverity severity,
589 const char* base_filename) {
590 assert(severity >= 0 && severity < NUM_SEVERITIES);
591 // Prevent any subtle race conditions by wrapping a mutex lock around
593 MutexLock l(&log_mutex);
594 log_destination(severity)->fileobject_.SetBasename(base_filename);
597 inline void LogDestination::SetLogSymlink(LogSeverity severity,
598 const char* symlink_basename) {
599 CHECK_GE(severity, 0);
600 CHECK_LT(severity, NUM_SEVERITIES);
601 MutexLock l(&log_mutex);
602 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
605 inline void LogDestination::AddLogSink(LogSink *destination) {
606 // Prevent any subtle race conditions by wrapping a mutex lock around
608 MutexLock l(&sink_mutex_);
609 if (!sinks_) sinks_ = new vector<LogSink*>;
610 sinks_->push_back(destination);
613 inline void LogDestination::RemoveLogSink(LogSink *destination) {
614 // Prevent any subtle race conditions by wrapping a mutex lock around
616 MutexLock l(&sink_mutex_);
617 // This doesn't keep the sinks in order, but who cares?
619 for (int i = sinks_->size() - 1; i >= 0; i--) {
620 if ((*sinks_)[i] == destination) {
621 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
629 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
630 // Prevent any subtle race conditions by wrapping a mutex lock around
632 MutexLock l(&log_mutex);
633 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
634 log_destination(severity)->fileobject_.SetExtension(ext);
638 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
639 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
640 // Prevent any subtle race conditions by wrapping a mutex lock around
642 MutexLock l(&log_mutex);
643 FLAGS_stderrthreshold = min_severity;
646 inline void LogDestination::LogToStderr() {
647 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
648 // SetLogDestination already do the locking!
649 SetStderrLogging(0); // thus everything is "also" logged to stderr
650 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
651 SetLogDestination(i, ""); // "" turns off logging to a logfile
655 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
656 const char* addresses) {
657 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
658 // Prevent any subtle race conditions by wrapping a mutex lock around
660 MutexLock l(&log_mutex);
661 LogDestination::email_logging_severity_ = min_severity;
662 LogDestination::addresses_ = addresses;
665 static void ColoredWriteToStderr(LogSeverity severity,
666 const char* message, size_t len) {
667 const GLogColor color =
668 (LogDestination::terminal_supports_color() && FLAGS_colorlogtostderr) ?
669 SeverityToColor(severity) : COLOR_DEFAULT;
671 // Avoid using cerr from this module since we may get called during
672 // exit code, and cerr may be partially or fully destroyed by then.
673 if (COLOR_DEFAULT == color) {
674 fwrite(message, len, 1, stderr);
678 const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
680 // Gets the current text color.
681 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
682 GetConsoleScreenBufferInfo(stderr_handle, &buffer_info);
683 const WORD old_color_attrs = buffer_info.wAttributes;
685 // We need to flush the stream buffers into the console before each
686 // SetConsoleTextAttribute call lest it affect the text that is already
687 // printed but has not yet reached the console.
689 SetConsoleTextAttribute(stderr_handle,
690 GetColorAttribute(color) | FOREGROUND_INTENSITY);
691 fwrite(message, len, 1, stderr);
693 // Restores the text color.
694 SetConsoleTextAttribute(stderr_handle, old_color_attrs);
696 fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color));
697 fwrite(message, len, 1, stderr);
698 fprintf(stderr, "\033[m"); // Resets the terminal to default.
702 static void WriteToStderr(const char* message, size_t len) {
703 // Avoid using cerr from this module since we may get called during
704 // exit code, and cerr may be partially or fully destroyed by then.
705 fwrite(message, len, 1, stderr);
708 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
709 const char* message, size_t len) {
710 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
711 ColoredWriteToStderr(severity, message, len);
713 // On Windows, also output to the debugger
714 ::OutputDebugStringA(string(message,len).c_str());
720 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
721 const char* message, size_t len) {
722 if (severity >= email_logging_severity_ ||
723 severity >= FLAGS_logemaillevel) {
724 string to(FLAGS_alsologtoemail);
725 if (!addresses_.empty()) {
731 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
732 glog_internal_namespace_::ProgramInvocationShortName());
733 string body(hostname());
735 body.append(message, len);
737 // should NOT use SendEmail(). The caller of this function holds the
738 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
739 // acquire the log_mutex object. Use SendEmailInternal() and set
740 // use_logging to false.
741 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
746 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
750 const bool should_flush = severity > FLAGS_logbuflevel;
751 LogDestination* destination = log_destination(severity);
752 destination->logger_->Write(should_flush, timestamp, message, len);
755 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
760 if ( FLAGS_logtostderr ) { // global flag: never log to file
761 ColoredWriteToStderr(severity, message, len);
763 for (int i = severity; i >= 0; --i)
764 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
768 inline void LogDestination::LogToSinks(LogSeverity severity,
769 const char *full_filename,
770 const char *base_filename,
772 const struct ::tm* tm_time,
774 size_t message_len) {
775 ReaderMutexLock l(&sink_mutex_);
777 for (int i = sinks_->size() - 1; i >= 0; i--) {
778 (*sinks_)[i]->send(severity, full_filename, base_filename,
779 line, tm_time, message, message_len);
784 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
785 ReaderMutexLock l(&sink_mutex_);
787 for (int i = sinks_->size() - 1; i >= 0; i--) {
788 (*sinks_)[i]->WaitTillSent();
791 const bool send_to_sink =
792 (data->send_method_ == &LogMessage::SendToSink) ||
793 (data->send_method_ == &LogMessage::SendToSinkAndLog);
794 if (send_to_sink && data->sink_ != NULL) {
795 data->sink_->WaitTillSent();
799 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
801 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
802 assert(severity >=0 && severity < NUM_SEVERITIES);
803 if (!log_destinations_[severity]) {
804 log_destinations_[severity] = new LogDestination(severity, NULL);
806 return log_destinations_[severity];
809 void LogDestination::DeleteLogDestinations() {
810 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
811 delete log_destinations_[severity];
812 log_destinations_[severity] = NULL;
818 LogFileObject::LogFileObject(LogSeverity severity,
819 const char* base_filename)
820 : base_filename_selected_(base_filename != NULL),
821 base_filename_((base_filename != NULL) ? base_filename : ""),
822 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
823 filename_extension_(),
826 bytes_since_flush_(0),
828 rollover_attempt_(kRolloverAttemptFrequency-1),
829 next_flush_time_(0) {
830 assert(severity >= 0);
831 assert(severity < NUM_SEVERITIES);
834 LogFileObject::~LogFileObject() {
842 void LogFileObject::SetBasename(const char* basename) {
844 base_filename_selected_ = true;
845 if (base_filename_ != basename) {
846 // Get rid of old log file since we are changing names
850 rollover_attempt_ = kRolloverAttemptFrequency-1;
852 base_filename_ = basename;
856 void LogFileObject::SetExtension(const char* ext) {
858 if (filename_extension_ != ext) {
859 // Get rid of old log file since we are changing names
863 rollover_attempt_ = kRolloverAttemptFrequency-1;
865 filename_extension_ = ext;
869 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
871 symlink_basename_ = symlink_basename;
874 void LogFileObject::Flush() {
879 void LogFileObject::FlushUnlocked(){
882 bytes_since_flush_ = 0;
884 // Figure out when we are due for another flush.
885 const int64 next = (FLAGS_logbufsecs
886 * static_cast<int64>(1000000)); // in usec
887 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
890 bool LogFileObject::CreateLogfile(const string& time_pid_string) {
891 string string_filename = base_filename_+filename_extension_+
893 const char* filename = string_filename.c_str();
894 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
895 if (fd == -1) return false;
897 // Mark the file close-on-exec. We don't really care if this fails
898 fcntl(fd, F_SETFD, FD_CLOEXEC);
901 file_ = fdopen(fd, "a"); // Make a FILE*.
902 if (file_ == NULL) { // Man, we're screwed!
904 unlink(filename); // Erase the half-baked evidence: an unusable log file
908 // We try to create a symlink called <program_name>.<severity>,
909 // which is easier to use. (Every time we create a new logfile,
910 // we destroy the old symlink and create a new one, so it always
911 // points to the latest logfile.) If it fails, we're sad but it's
913 if (!symlink_basename_.empty()) {
914 // take directory from filename
915 const char* slash = strrchr(filename, PATH_SEPARATOR);
916 const string linkname =
917 symlink_basename_ + '.' + LogSeverityNames[severity_];
919 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
920 linkpath += linkname;
921 unlink(linkpath.c_str()); // delete old one if it exists
923 #if defined(OS_WINDOWS)
924 // TODO(hamaji): Create lnk file on Windows?
925 #elif defined(HAVE_UNISTD_H)
926 // We must have unistd.h.
927 // Make the symlink be relative (in the same dir) so that if the
928 // entire log directory gets relocated the link is still valid.
929 const char *linkdest = slash ? (slash + 1) : filename;
930 if (symlink(linkdest, linkpath.c_str()) != 0) {
931 // silently ignore failures
934 // Make an additional link to the log file in a place specified by
935 // FLAGS_log_link, if indicated
936 if (!FLAGS_log_link.empty()) {
937 linkpath = FLAGS_log_link + "/" + linkname;
938 unlink(linkpath.c_str()); // delete old one if it exists
939 if (symlink(filename, linkpath.c_str()) != 0) {
940 // silently ignore failures
946 return true; // Everything worked
949 void LogFileObject::Write(bool force_flush,
955 // We don't log if the base_name_ is "" (which means "don't write")
956 if (base_filename_selected_ && base_filename_.empty()) {
960 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
962 if (file_ != NULL) fclose(file_);
964 file_length_ = bytes_since_flush_ = 0;
965 rollover_attempt_ = kRolloverAttemptFrequency-1;
968 // If there's no destination file, make one before outputting
970 // Try to rollover the log file every 32 log messages. The only time
971 // this could matter would be when we have trouble creating the log
972 // file. If that happens, we'll lose lots of log messages, of course!
973 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
974 rollover_attempt_ = 0;
977 localtime_r(×tamp, &tm_time);
979 // The logfile's filename will have the date/time & pid in it
980 ostringstream time_pid_stream;
981 time_pid_stream.fill('0');
982 time_pid_stream << 1900+tm_time.tm_year
983 << setw(2) << 1+tm_time.tm_mon
984 << setw(2) << tm_time.tm_mday
986 << setw(2) << tm_time.tm_hour
987 << setw(2) << tm_time.tm_min
988 << setw(2) << tm_time.tm_sec
990 << GetMainThreadPid();
991 const string& time_pid_string = time_pid_stream.str();
993 if (base_filename_selected_) {
994 if (!CreateLogfile(time_pid_string)) {
995 perror("Could not create log file");
996 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
997 time_pid_string.c_str());
1001 // If no base filename for logs of this severity has been set, use a
1002 // default base filename of
1003 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
1004 // logfiles will have names like
1005 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
1006 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
1007 // and 4354 is the pid of the logging process. The date & time reflect
1008 // when the file was created for output.
1010 // Where does the file get put? Successively try the directories
1012 string stripped_filename(
1013 glog_internal_namespace_::ProgramInvocationShortName());
1015 GetHostName(&hostname);
1017 string uidname = MyUserName();
1018 // We should not call CHECK() here because this function can be
1019 // called after holding on to log_mutex. We don't want to
1020 // attempt to hold on to the same mutex, and get into a
1021 // deadlock. Simply use a name like invalid-user.
1022 if (uidname.empty()) uidname = "invalid-user";
1024 stripped_filename = stripped_filename+'.'+hostname+'.'
1026 +LogSeverityNames[severity_]+'.';
1027 // We're going to (potentially) try to put logs in several different dirs
1028 const vector<string> & log_dirs = GetLoggingDirectories();
1030 // Go through the list of dirs, and try to create the log file in each
1031 // until we succeed or run out of options
1032 bool success = false;
1033 for (vector<string>::const_iterator dir = log_dirs.begin();
1034 dir != log_dirs.end();
1036 base_filename_ = *dir + "/" + stripped_filename;
1037 if ( CreateLogfile(time_pid_string) ) {
1042 // If we never succeeded, we have to give up
1043 if ( success == false ) {
1044 perror("Could not create logging file");
1045 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
1046 time_pid_string.c_str());
1051 // Write a header message into the log file
1052 ostringstream file_header_stream;
1053 file_header_stream.fill('0');
1054 file_header_stream << "Log file created at: "
1055 << 1900+tm_time.tm_year << '/'
1056 << setw(2) << 1+tm_time.tm_mon << '/'
1057 << setw(2) << tm_time.tm_mday
1059 << setw(2) << tm_time.tm_hour << ':'
1060 << setw(2) << tm_time.tm_min << ':'
1061 << setw(2) << tm_time.tm_sec << '\n'
1062 << "Running on machine: "
1063 << LogDestination::hostname() << '\n'
1064 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
1065 << "threadid file:line] msg" << '\n';
1066 const string& file_header_string = file_header_stream.str();
1068 const int header_len = file_header_string.size();
1069 fwrite(file_header_string.data(), 1, header_len, file_);
1070 file_length_ += header_len;
1071 bytes_since_flush_ += header_len;
1074 // Write to LOG file
1075 if ( !stop_writing ) {
1076 // fwrite() doesn't return an error when the disk is full, for
1077 // messages that are less than 4096 bytes. When the disk is full,
1078 // it returns the message length for messages that are less than
1079 // 4096 bytes. fwrite() returns 4096 for message lengths that are
1080 // greater than 4096, thereby indicating an error.
1082 fwrite(message, 1, message_len, file_);
1083 if ( FLAGS_stop_logging_if_full_disk &&
1084 errno == ENOSPC ) { // disk full, stop writing to disk
1085 stop_writing = true; // until the disk is
1088 file_length_ += message_len;
1089 bytes_since_flush_ += message_len;
1092 if ( CycleClock_Now() >= next_flush_time_ )
1093 stop_writing = false; // check to see if disk has free space.
1094 return; // no need to flush
1097 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
1098 // or every "FLAGS_logbufsecs" seconds.
1100 (bytes_since_flush_ >= 1000000) ||
1101 (CycleClock_Now() >= next_flush_time_) ) {
1104 if (FLAGS_drop_log_memory) {
1105 if (file_length_ >= logging::kPageSize) {
1106 // don't evict the most recent page
1107 uint32 len = file_length_ & ~(logging::kPageSize - 1);
1108 posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
1118 // Static log data space to avoid alloc failures in a LOG(FATAL)
1120 // Since multiple threads may call LOG(FATAL), and we want to preserve
1121 // the data from the first call, we allocate two sets of space. One
1122 // for exclusive use by the first thread, and one for shared use by
1123 // all other threads.
1124 static Mutex fatal_msg_lock;
1125 static CrashReason crash_reason;
1126 static bool fatal_msg_exclusive = true;
1127 static LogMessage::LogMessageData fatal_msg_data_exclusive;
1128 static LogMessage::LogMessageData fatal_msg_data_shared;
1130 LogMessage::LogMessageData::LogMessageData()
1131 : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) {
1134 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1135 int ctr, void (LogMessage::*send_method)())
1136 : allocated_(NULL) {
1137 Init(file, line, severity, send_method);
1138 data_->stream_.set_ctr(ctr);
1141 LogMessage::LogMessage(const char* file, int line,
1142 const CheckOpString& result)
1143 : allocated_(NULL) {
1144 Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
1145 stream() << "Check failed: " << (*result.str_) << " ";
1148 LogMessage::LogMessage(const char* file, int line)
1149 : allocated_(NULL) {
1150 Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
1153 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
1154 : allocated_(NULL) {
1155 Init(file, line, severity, &LogMessage::SendToLog);
1158 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1159 LogSink* sink, bool also_send_to_log)
1160 : allocated_(NULL) {
1161 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
1162 &LogMessage::SendToSink);
1163 data_->sink_ = sink; // override Init()'s setting to NULL
1166 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1167 vector<string> *outvec)
1168 : allocated_(NULL) {
1169 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
1170 data_->outvec_ = outvec; // override Init()'s setting to NULL
1173 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1175 : allocated_(NULL) {
1176 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
1177 data_->message_ = message; // override Init()'s setting to NULL
1180 void LogMessage::Init(const char* file,
1182 LogSeverity severity,
1183 void (LogMessage::*send_method)()) {
1185 if (severity != GLOG_FATAL || !exit_on_dfatal) {
1186 allocated_ = new LogMessageData();
1188 data_->first_fatal_ = false;
1190 MutexLock l(&fatal_msg_lock);
1191 if (fatal_msg_exclusive) {
1192 fatal_msg_exclusive = false;
1193 data_ = &fatal_msg_data_exclusive;
1194 data_->first_fatal_ = true;
1196 data_ = &fatal_msg_data_shared;
1197 data_->first_fatal_ = false;
1202 data_->preserved_errno_ = errno;
1203 data_->severity_ = severity;
1204 data_->line_ = line;
1205 data_->send_method_ = send_method;
1206 data_->sink_ = NULL;
1207 data_->outvec_ = NULL;
1208 WallTime now = WallTime_Now();
1209 data_->timestamp_ = static_cast<time_t>(now);
1210 localtime_r(&data_->timestamp_, &data_->tm_time_);
1211 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1212 RawLog__SetLastTime(data_->tm_time_, usecs);
1214 data_->num_chars_to_log_ = 0;
1215 data_->num_chars_to_syslog_ = 0;
1216 data_->basename_ = const_basename(file);
1217 data_->fullname_ = file;
1218 data_->has_been_flushed_ = false;
1220 // If specified, prepend a prefix to each line. For example:
1221 // I1018 160715 f5d4fbb0 logging.cc:1153]
1222 // (log level, GMT month, date, time, thread_id, file basename, line)
1223 // We exclude the thread_id for the default thread.
1224 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1225 stream() << LogSeverityNames[severity][0]
1226 << setw(2) << 1+data_->tm_time_.tm_mon
1227 << setw(2) << data_->tm_time_.tm_mday
1229 << setw(2) << data_->tm_time_.tm_hour << ':'
1230 << setw(2) << data_->tm_time_.tm_min << ':'
1231 << setw(2) << data_->tm_time_.tm_sec << "."
1234 << setfill(' ') << setw(5)
1235 << static_cast<unsigned int>(GetTID()) << setfill('0')
1237 << data_->basename_ << ':' << data_->line_ << "] ";
1239 data_->num_prefix_chars_ = data_->stream_.pcount();
1241 if (!FLAGS_log_backtrace_at.empty()) {
1243 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1244 #ifdef HAVE_STACKTRACE
1245 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1247 DumpStackTraceToString(&stacktrace);
1248 stream() << " (stacktrace:\n" << stacktrace << ") ";
1254 LogMessage::~LogMessage() {
1259 int LogMessage::preserved_errno() const {
1260 return data_->preserved_errno_;
1263 ostream& LogMessage::stream() {
1264 return data_->stream_;
1267 // Flush buffered message, called by the destructor, or any other function
1268 // that needs to synchronize the log.
1269 void LogMessage::Flush() {
1270 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1273 data_->num_chars_to_log_ = data_->stream_.pcount();
1274 data_->num_chars_to_syslog_ =
1275 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1277 // Do we need to add a \n to the end of this message?
1278 bool append_newline =
1279 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1280 char original_final_char = '\0';
1282 // If we do need to add a \n, we'll do it by violating the memory of the
1283 // ostrstream buffer. This is quick, and we'll make sure to undo our
1284 // modification before anything else is done with the ostrstream. It
1285 // would be preferable not to do things this way, but it seems to be
1286 // the best way to deal with this.
1287 if (append_newline) {
1288 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1289 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1292 // Prevent any subtle race conditions by wrapping a mutex lock around
1293 // the actual logging action per se.
1295 MutexLock l(&log_mutex);
1296 (this->*(data_->send_method_))();
1297 ++num_messages_[static_cast<int>(data_->severity_)];
1299 LogDestination::WaitForSinks(data_);
1301 if (append_newline) {
1302 // Fix the ostrstream back how it was before we screwed with it.
1303 // It's 99.44% certain that we don't need to worry about doing this.
1304 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1307 // If errno was already set before we enter the logging call, we'll
1308 // set it back to that value when we return from the logging call.
1309 // It happens often that we log an error message after a syscall
1310 // failure, which can potentially set the errno to some other
1311 // values. We would like to preserve the original errno.
1312 if (data_->preserved_errno_ != 0) {
1313 errno = data_->preserved_errno_;
1316 // Note that this message is now safely logged. If we're asked to flush
1317 // again, as a result of destruction, say, we'll do nothing on future calls.
1318 data_->has_been_flushed_ = true;
1321 // Copy of first FATAL log message so that we can print it out again
1322 // after all the stack traces. To preserve legacy behavior, we don't
1323 // use fatal_msg_data_exclusive.
1324 static time_t fatal_time;
1325 static char fatal_message[256];
1327 void ReprintFatalMessage() {
1328 if (fatal_message[0]) {
1329 const int n = strlen(fatal_message);
1330 if (!FLAGS_logtostderr) {
1331 // Also write to stderr (don't color to avoid terminal checks)
1332 WriteToStderr(fatal_message, n);
1334 LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1338 // L >= log_mutex (callers must hold the log_mutex).
1339 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1340 static bool already_warned_before_initgoogle = false;
1342 log_mutex.AssertHeld();
1344 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1345 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1347 // Messages of a given severity get logged to lower severity logs, too
1349 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1350 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1351 "written to STDERR\n";
1352 WriteToStderr(w, strlen(w));
1353 already_warned_before_initgoogle = true;
1356 // global flag: never log to file if set. Also -- don't log to a
1357 // file if we haven't parsed the command line flags to get the
1359 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1360 ColoredWriteToStderr(data_->severity_,
1361 data_->message_text_, data_->num_chars_to_log_);
1363 // this could be protected by a flag if necessary.
1364 LogDestination::LogToSinks(data_->severity_,
1365 data_->fullname_, data_->basename_,
1366 data_->line_, &data_->tm_time_,
1367 data_->message_text_ + data_->num_prefix_chars_,
1368 (data_->num_chars_to_log_ -
1369 data_->num_prefix_chars_ - 1));
1372 // log this message to all log files of severity <= severity_
1373 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1374 data_->message_text_,
1375 data_->num_chars_to_log_);
1377 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1378 data_->num_chars_to_log_);
1379 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1380 data_->num_chars_to_log_);
1381 LogDestination::LogToSinks(data_->severity_,
1382 data_->fullname_, data_->basename_,
1383 data_->line_, &data_->tm_time_,
1384 data_->message_text_ + data_->num_prefix_chars_,
1385 (data_->num_chars_to_log_
1386 - data_->num_prefix_chars_ - 1));
1387 // NOTE: -1 removes trailing \n
1390 // If we log a FATAL message, flush all the log destinations, then toss
1391 // a signal for others to catch. We leave the logs in a state that
1392 // someone else can use them (as long as they flush afterwards)
1393 if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1394 if (data_->first_fatal_) {
1395 // Store crash information so that it is accessible from within signal
1396 // handlers that may be invoked later.
1397 RecordCrashReason(&crash_reason);
1398 SetCrashReason(&crash_reason);
1400 // Store shortened fatal message for other logs and GWQ status
1401 const int copy = min<int>(data_->num_chars_to_log_,
1402 sizeof(fatal_message)-1);
1403 memcpy(fatal_message, data_->message_text_, copy);
1404 fatal_message[copy] = '\0';
1405 fatal_time = data_->timestamp_;
1408 if (!FLAGS_logtostderr) {
1409 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1410 if ( LogDestination::log_destinations_[i] )
1411 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1415 // release the lock that our caller (directly or indirectly)
1416 // LogMessage::~LogMessage() grabbed so that signal handlers
1417 // can use the logging facility. Alternately, we could add
1418 // an entire unsafe logging interface to bypass locking
1419 // for signal handlers but this seems simpler.
1421 LogDestination::WaitForSinks(data_);
1423 const char* message = "*** Check failure stack trace: ***\n";
1424 if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1431 void LogMessage::RecordCrashReason(
1432 glog_internal_namespace_::CrashReason* reason) {
1433 reason->filename = fatal_msg_data_exclusive.fullname_;
1434 reason->line_number = fatal_msg_data_exclusive.line_;
1435 reason->message = fatal_msg_data_exclusive.message_text_ +
1436 fatal_msg_data_exclusive.num_prefix_chars_;
1437 #ifdef HAVE_STACKTRACE
1438 // Retrieve the stack trace, omitting the logging frames that got us here.
1439 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1445 #ifdef HAVE___ATTRIBUTE__
1446 # define ATTRIBUTE_NORETURN __attribute__((noreturn))
1448 # define ATTRIBUTE_NORETURN
1451 static void logging_fail() ATTRIBUTE_NORETURN;
1453 static void logging_fail() {
1454 #if defined(_DEBUG) && defined(_MSC_VER)
1455 // When debugging on windows, avoid the obnoxious dialog and make
1456 // it possible to continue past a LOG(FATAL) in the debugger
1463 typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN;
1465 GOOGLE_GLOG_DLL_DECL
1466 logging_fail_func_t g_logging_fail_func = &logging_fail;
1468 void InstallFailureFunction(void (*fail_func)()) {
1469 g_logging_fail_func = (logging_fail_func_t)fail_func;
1472 void LogMessage::Fail() {
1473 g_logging_fail_func();
1476 // L >= log_mutex (callers must hold the log_mutex).
1477 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1478 if (data_->sink_ != NULL) {
1479 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1480 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1481 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1482 data_->line_, &data_->tm_time_,
1483 data_->message_text_ + data_->num_prefix_chars_,
1484 (data_->num_chars_to_log_ -
1485 data_->num_prefix_chars_ - 1));
1489 // L >= log_mutex (callers must hold the log_mutex).
1490 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1495 // L >= log_mutex (callers must hold the log_mutex).
1496 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1497 if (data_->outvec_ != NULL) {
1498 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1499 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1500 // Omit prefix of message and trailing newline when recording in outvec_.
1501 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1502 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1503 data_->outvec_->push_back(string(start, len));
1509 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1510 if (data_->message_ != NULL) {
1511 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1512 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1513 // Omit prefix of message and trailing newline when writing to message_.
1514 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1515 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1516 data_->message_->assign(start, len);
1521 // L >= log_mutex (callers must hold the log_mutex).
1522 void LogMessage::SendToSyslogAndLog() {
1523 #ifdef HAVE_SYSLOG_H
1524 // Before any calls to syslog(), make a single call to openlog()
1525 static bool openlog_already_called = false;
1526 if (!openlog_already_called) {
1527 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1528 LOG_CONS | LOG_NDELAY | LOG_PID,
1530 openlog_already_called = true;
1533 // This array maps Google severity levels to syslog levels
1534 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1535 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1536 int(data_->num_chars_to_syslog_),
1537 data_->message_text_ + data_->num_prefix_chars_);
1540 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1544 base::Logger* base::GetLogger(LogSeverity severity) {
1545 MutexLock l(&log_mutex);
1546 return LogDestination::log_destination(severity)->logger_;
1549 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1550 MutexLock l(&log_mutex);
1551 LogDestination::log_destination(severity)->logger_ = logger;
1554 // L < log_mutex. Acquires and releases mutex_.
1555 int64 LogMessage::num_messages(int severity) {
1556 MutexLock l(&log_mutex);
1557 return num_messages_[severity];
1560 // Output the COUNTER value. This is only valid if ostream is a
1562 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1564 LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
1566 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1568 CHECK(log && log == log->self())
1569 << "You must not use COUNTER with non-glog ostream";
1574 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1575 LogSeverity severity, int ctr,
1576 void (LogMessage::*send_method)())
1577 : LogMessage(file, line, severity, ctr, send_method) {
1580 ErrnoLogMessage::~ErrnoLogMessage() {
1581 // Don't access errno directly because it may have been altered
1582 // while streaming the message.
1583 stream() << ": " << StrError(preserved_errno()) << " ["
1584 << preserved_errno() << "]";
1587 void FlushLogFiles(LogSeverity min_severity) {
1588 LogDestination::FlushLogFiles(min_severity);
1591 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1592 LogDestination::FlushLogFilesUnsafe(min_severity);
1595 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1596 LogDestination::SetLogDestination(severity, base_filename);
1599 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1600 LogDestination::SetLogSymlink(severity, symlink_basename);
1603 LogSink::~LogSink() {
1606 void LogSink::WaitTillSent() {
1610 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1611 const struct ::tm* tm_time,
1612 const char* message, size_t message_len) {
1613 ostringstream stream(string(message, message_len));
1616 // FIXME(jrvb): Updating this to use the correct value for usecs
1617 // requires changing the signature for both this method and
1618 // LogSink::send(). This change needs to be done in a separate CL
1619 // so subclasses of LogSink can be updated at the same time.
1622 stream << LogSeverityNames[severity][0]
1623 << setw(2) << 1+tm_time->tm_mon
1624 << setw(2) << tm_time->tm_mday
1626 << setw(2) << tm_time->tm_hour << ':'
1627 << setw(2) << tm_time->tm_min << ':'
1628 << setw(2) << tm_time->tm_sec << '.'
1631 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1633 << file << ':' << line << "] ";
1635 stream << string(message, message_len);
1636 return stream.str();
1639 void AddLogSink(LogSink *destination) {
1640 LogDestination::AddLogSink(destination);
1643 void RemoveLogSink(LogSink *destination) {
1644 LogDestination::RemoveLogSink(destination);
1647 void SetLogFilenameExtension(const char* ext) {
1648 LogDestination::SetLogFilenameExtension(ext);
1651 void SetStderrLogging(LogSeverity min_severity) {
1652 LogDestination::SetStderrLogging(min_severity);
1655 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1656 LogDestination::SetEmailLogging(min_severity, addresses);
1659 void LogToStderr() {
1660 LogDestination::LogToStderr();
1664 namespace internal {
1666 bool GetExitOnDFatal() {
1667 MutexLock l(&log_mutex);
1668 return exit_on_dfatal;
1671 // Determines whether we exit the program for a LOG(DFATAL) message in
1672 // debug mode. It does this by skipping the call to Fail/FailQuietly.
1673 // This is intended for testing only.
1675 // This can have some effects on LOG(FATAL) as well. Failure messages
1676 // are always allocated (rather than sharing a buffer), the crash
1677 // reason is not recorded, the "gwq" status message is not updated,
1678 // and the stack trace is not recorded. The LOG(FATAL) *will* still
1679 // exit the program. Since this function is used only in testing,
1680 // these differences are acceptable.
1681 void SetExitOnDFatal(bool value) {
1682 MutexLock l(&log_mutex);
1683 exit_on_dfatal = value;
1686 } // namespace internal
1689 // use_logging controls whether the logging functions LOG/VLOG are used
1690 // to log errors. It should be set to false when the caller holds the
1692 static bool SendEmailInternal(const char*dest, const char *subject,
1693 const char*body, bool use_logging) {
1694 if (dest && *dest) {
1695 if ( use_logging ) {
1696 VLOG(1) << "Trying to send TITLE:" << subject
1697 << " BODY:" << body << " to " << dest;
1699 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1700 subject, body, dest);
1704 FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1705 FILE* pipe = popen(cmd.c_str(), "w");
1707 // Add the body if we have one
1709 fwrite(body, sizeof(char), strlen(body), pipe);
1710 bool ok = pclose(pipe) != -1;
1712 if ( use_logging ) {
1713 LOG(ERROR) << "Problems sending mail to " << dest << ": "
1716 fprintf(stderr, "Problems sending mail to %s: %s\n",
1717 dest, StrError(errno).c_str());
1722 if ( use_logging ) {
1723 LOG(ERROR) << "Unable to send mail to " << dest;
1725 fprintf(stderr, "Unable to send mail to %s\n", dest);
1732 bool SendEmail(const char*dest, const char *subject, const char*body){
1733 return SendEmailInternal(dest, subject, body, true);
1736 static void GetTempDirectories(vector<string>* list) {
1739 // On windows we'll try to find a directory in this order:
1740 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1743 // C:/WINDOWS/ or C:/WINNT/
1746 if (GetTempPathA(MAX_PATH, tmp))
1747 list->push_back(tmp);
1748 list->push_back("C:\\tmp\\");
1749 list->push_back("C:\\temp\\");
1751 // Directories, in order of preference. If we find a dir that
1752 // exists, we stop adding other less-preferred dirs
1753 const char * candidates[] = {
1754 // Non-null only during unittest/regtest
1755 getenv("TEST_TMPDIR"),
1757 // Explicitly-supplied temp dirs
1758 getenv("TMPDIR"), getenv("TMP"),
1760 // If all else fails
1764 for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
1765 const char *d = candidates[i];
1766 if (!d) continue; // Empty env var
1768 // Make sure we don't surprise anyone who's expecting a '/'
1770 if (dstr[dstr.size() - 1] != '/') {
1773 list->push_back(dstr);
1775 struct stat statbuf;
1776 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1777 // We found a dir that exists - we're done.
1785 static vector<string>* logging_directories_list;
1787 const vector<string>& GetLoggingDirectories() {
1788 // Not strictly thread-safe but we're called early in InitGoogle().
1789 if (logging_directories_list == NULL) {
1790 logging_directories_list = new vector<string>;
1792 if ( !FLAGS_log_dir.empty() ) {
1793 // A dir was specified, we should use it
1794 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1796 GetTempDirectories(logging_directories_list);
1799 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1800 logging_directories_list->push_back(tmp);
1801 logging_directories_list->push_back(".\\");
1803 logging_directories_list->push_back("./");
1807 return *logging_directories_list;
1810 void TestOnly_ClearLoggingDirectoriesList() {
1811 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1812 "called from test code.\n");
1813 delete logging_directories_list;
1814 logging_directories_list = NULL;
1817 void GetExistingTempDirectories(vector<string>* list) {
1818 GetTempDirectories(list);
1819 vector<string>::iterator i_dir = list->begin();
1820 while( i_dir != list->end() ) {
1821 // zero arg to access means test for existence; no constant
1822 // defined on windows
1823 if ( access(i_dir->c_str(), 0) ) {
1824 i_dir = list->erase(i_dir);
1831 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1832 #ifdef HAVE_UNISTD_H
1833 struct stat statbuf;
1834 const int kCopyBlockSize = 8 << 10;
1835 char copybuf[kCopyBlockSize];
1836 int64 read_offset, write_offset;
1837 // Don't follow symlinks unless they're our own fd symlinks in /proc
1839 // TODO(hamaji): Support other environments.
1841 const char *procfd_prefix = "/proc/self/fd/";
1842 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1845 int fd = open(path, flags);
1847 if (errno == EFBIG) {
1848 // The log file in question has got too big for us to open. The
1849 // real fix for this would be to compile logging.cc (or probably
1850 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1852 // Instead just truncate the file to something we can manage
1853 if (truncate(path, 0) == -1) {
1854 PLOG(ERROR) << "Unable to truncate " << path;
1856 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1859 PLOG(ERROR) << "Unable to open " << path;
1864 if (fstat(fd, &statbuf) == -1) {
1865 PLOG(ERROR) << "Unable to fstat()";
1869 // See if the path refers to a regular file bigger than the
1871 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1872 if (statbuf.st_size <= limit) goto out_close_fd;
1873 if (statbuf.st_size <= keep) goto out_close_fd;
1875 // This log file is too large - we need to truncate it
1876 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1878 // Copy the last "keep" bytes of the file to the beginning of the file
1879 read_offset = statbuf.st_size - keep;
1881 int bytesin, bytesout;
1882 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1883 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1884 if (bytesout == -1) {
1885 PLOG(ERROR) << "Unable to write to " << path;
1887 } else if (bytesout != bytesin) {
1888 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1890 read_offset += bytesin;
1891 write_offset += bytesout;
1893 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1895 // Truncate the remainder of the file. If someone else writes to the
1896 // end of the file after our last read() above, we lose their latest
1897 // data. Too bad ...
1898 if (ftruncate(fd, write_offset) == -1) {
1899 PLOG(ERROR) << "Unable to truncate " << path;
1905 LOG(ERROR) << "No log truncation support.";
1909 void TruncateStdoutStderr() {
1910 #ifdef HAVE_UNISTD_H
1911 int64 limit = MaxLogSize() << 20;
1912 int64 keep = 1 << 20;
1913 TruncateLogFile("/proc/self/fd/1", limit, keep);
1914 TruncateLogFile("/proc/self/fd/2", limit, keep);
1916 LOG(ERROR) << "No log truncation support.";
1921 // Helper functions for string comparisons.
1922 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1923 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1924 const char* names) { \
1925 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1926 if (equal == expected) return NULL; \
1931 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1932 return new string(ss.str()); \
1935 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1936 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1937 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1938 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1939 #undef DEFINE_CHECK_STROP_IMPL
1941 int posix_strerror_r(int err, char *buf, size_t len) {
1942 // Sanity check input parameters
1943 if (buf == NULL || len <= 0) {
1948 // Reset buf and errno, and try calling whatever version of strerror_r()
1949 // is implemented by glibc
1951 int old_errno = errno;
1953 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1955 // Both versions set errno on failure
1957 // Should already be there, but better safe than sorry
1963 // POSIX is vague about whether the string will be terminated, although
1964 // is indirectly implies that typically ERANGE will be returned, instead
1965 // of truncating the string. This is different from the GNU implementation.
1966 // We play it safe by always terminating the string explicitly.
1967 buf[len-1] = '\000';
1969 // If the function succeeded, we can use its exit code to determine the
1970 // semantics implemented by glibc
1974 // GNU semantics detected
1979 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
1980 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
1981 // This means an error on MacOSX or FreeBSD.
1985 strncat(buf, rc, len-1);
1991 string StrError(int err) {
1993 int rc = posix_strerror_r(err, buf, sizeof(buf));
1994 if ((rc < 0) || (buf[0] == '\000')) {
1995 snprintf(buf, sizeof(buf), "Error number %d", err);
2000 LogMessageFatal::LogMessageFatal(const char* file, int line) :
2001 LogMessage(file, line, GLOG_FATAL) {}
2003 LogMessageFatal::LogMessageFatal(const char* file, int line,
2004 const CheckOpString& result) :
2005 LogMessage(file, line, result) {}
2007 LogMessageFatal::~LogMessageFatal() {
2014 CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
2015 : stream_(new ostringstream) {
2016 *stream_ << exprtext << " (";
2019 CheckOpMessageBuilder::~CheckOpMessageBuilder() {
2023 ostream* CheckOpMessageBuilder::ForVar2() {
2024 *stream_ << " vs. ";
2028 string* CheckOpMessageBuilder::NewString() {
2030 return new string(stream_->str());
2036 void MakeCheckOpValueString(std::ostream* os, const char& v) {
2037 if (v >= 32 && v <= 126) {
2038 (*os) << "'" << v << "'";
2040 (*os) << "char value " << (short)v;
2045 void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
2046 if (v >= 32 && v <= 126) {
2047 (*os) << "'" << v << "'";
2049 (*os) << "signed char value " << (short)v;
2054 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
2055 if (v >= 32 && v <= 126) {
2056 (*os) << "'" << v << "'";
2058 (*os) << "unsigned char value " << (unsigned short)v;
2062 void InitGoogleLogging(const char* argv0) {
2063 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
2066 void ShutdownGoogleLogging() {
2067 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
2068 LogDestination::DeleteLogDestinations();
2069 delete logging_directories_list;
2070 logging_directories_list = NULL;
2073 _END_GOOGLE_NAMESPACE_