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");
106 GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
107 "Logs can grow very quickly and they are rarely read before they "
108 "need to be evicted from memory. Instead, drop them from memory "
109 "as soon as they are flushed to disk.");
110 _START_GOOGLE_NAMESPACE_
112 static const int64 kPageSize = getpagesize();
114 _END_GOOGLE_NAMESPACE_
117 // By default, errors (including fatal errors) get logged to stderr as
120 // The default is ERROR instead of FATAL so that users can see problems
121 // when they run a program without having to look in another file.
122 DEFINE_int32(stderrthreshold,
123 GOOGLE_NAMESPACE::GLOG_ERROR,
124 "log messages at or above this level are copied to stderr in "
125 "addition to logfiles. This flag obsoletes --alsologtostderr.");
127 GLOG_DEFINE_string(alsologtoemail, "",
128 "log messages go to these email addresses "
129 "in addition to logfiles");
130 GLOG_DEFINE_bool(log_prefix, true,
131 "Prepend the log prefix to the start of each log line");
132 GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
133 "actually get logged anywhere");
134 GLOG_DEFINE_int32(logbuflevel, 0,
135 "Buffer log messages logged at this level or lower"
136 " (-1 means don't buffer; 0 means buffer INFO only;"
138 GLOG_DEFINE_int32(logbufsecs, 30,
139 "Buffer log messages for at most this many seconds");
140 GLOG_DEFINE_int32(logemaillevel, 999,
141 "Email log messages logged at this level or higher"
142 " (0 means email all; 3 means email FATAL only;"
144 GLOG_DEFINE_string(logmailer, "/bin/mail",
145 "Mailer used to send logging email");
147 // Compute the default value for --log_dir
148 static const char* DefaultLogDir() {
150 env = getenv("GOOGLE_LOG_DIR");
151 if (env != NULL && env[0] != '\0') {
154 env = getenv("TEST_TMPDIR");
155 if (env != NULL && env[0] != '\0') {
161 GLOG_DEFINE_string(log_dir, DefaultLogDir(),
162 "If specified, logfiles are written into this directory instead "
163 "of the default logging directory.");
164 GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
165 "files in this directory");
167 GLOG_DEFINE_int32(max_log_size, 1800,
168 "approx. maximum log file size (in MB). A value of 0 will "
169 "be silently overridden to 1.");
171 GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
172 "Stop attempting to log to disk if the disk is full.");
174 GLOG_DEFINE_string(log_backtrace_at, "",
175 "Emit a backtrace when logging at file:linenum.");
177 // TODO(hamaji): consider windows
178 #define PATH_SEPARATOR '/'
180 static void GetHostName(string* hostname) {
181 #if defined(HAVE_SYS_UTSNAME_H)
183 if (0 != uname(&buf)) {
184 // ensure null termination on failure
185 *buf.nodename = '\0';
187 *hostname = buf.nodename;
188 #elif defined(OS_WINDOWS)
189 char buf[MAX_COMPUTERNAME_LENGTH + 1];
190 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
191 if (GetComputerNameA(buf, &len)) {
197 # warning There is no way to retrieve the host name.
198 *hostname = "(unknown)";
202 _START_GOOGLE_NAMESPACE_
204 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
205 static int32 MaxLogSize() {
206 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
209 struct LogMessage::LogMessageData {
212 int preserved_errno_; // preserved errno
213 char* buf_; // buffer space for non FATAL messages
214 char* message_text_; // Complete message text (points to selected buffer)
215 LogStream* stream_alloc_;
217 char severity_; // What level is this LogMessage logged at?
218 int line_; // line number where logging call is.
219 void (LogMessage::*send_method_)(); // Call this in destructor to send
220 union { // At most one of these is used: union to keep the size low.
221 LogSink* sink_; // NULL or sink to send message to
222 std::vector<std::string>* outvec_; // NULL or vector to push message onto
223 std::string* message_; // NULL or string to write message into
225 time_t timestamp_; // Time of creation of LogMessage
226 struct ::tm tm_time_; // Time of creation of LogMessage
227 size_t num_prefix_chars_; // # of chars of prefix in this message
228 size_t num_chars_to_log_; // # of chars of msg to send to log
229 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
230 const char* basename_; // basename of file that called LOG
231 const char* fullname_; // fullname of file that called LOG
232 bool has_been_flushed_; // false => data has not been flushed
233 bool first_fatal_; // true => this was first fatal msg
238 LogMessageData(const LogMessageData&);
239 void operator=(const LogMessageData&);
242 // A mutex that allows only one thread to log at a time, to keep things from
243 // getting jumbled. Some other very uncommon logging operations (like
244 // changing the destination file for log messages of a given severity) also
245 // lock this mutex. Please be sure that anybody who might possibly need to
247 static Mutex log_mutex;
249 // Number of messages sent at each severity. Under log_mutex.
250 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
252 // Globally disable log writing (if disk is full)
253 static bool stop_writing = false;
255 const char*const LogSeverityNames[NUM_SEVERITIES] = {
256 "INFO", "WARNING", "ERROR", "FATAL"
259 // Has the user called SetExitOnDFatal(true)?
260 static bool exit_on_dfatal = true;
262 const char* GetLogSeverityName(LogSeverity severity) {
263 return LogSeverityNames[severity];
266 static bool SendEmailInternal(const char*dest, const char *subject,
267 const char*body, bool use_logging);
269 base::Logger::~Logger() {
274 // Encapsulates all file-system related state
275 class LogFileObject : public base::Logger {
277 LogFileObject(LogSeverity severity, const char* base_filename);
280 virtual void Write(bool force_flush, // Should we force a flush here?
281 time_t timestamp, // Timestamp for this entry
285 // Configuration options
286 void SetBasename(const char* basename);
287 void SetExtension(const char* ext);
288 void SetSymlinkBasename(const char* symlink_basename);
290 // Normal flushing routine
291 virtual void Flush();
293 // It is the actual file length for the system loggers,
294 // i.e., INFO, ERROR, etc.
295 virtual uint32 LogSize() {
300 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
301 // can avoid grabbing a lock. Usually Flush() calls it after
303 void FlushUnlocked();
306 static const uint32 kRolloverAttemptFrequency = 0x20;
309 bool base_filename_selected_;
310 string base_filename_;
311 string symlink_basename_;
312 string filename_extension_; // option users can specify (eg to add port#)
314 LogSeverity severity_;
315 uint32 bytes_since_flush_;
317 unsigned int rollover_attempt_;
318 int64 next_flush_time_; // cycle count at which to flush log
320 // Actually create a logfile using the value of base_filename_ and the
321 // supplied argument time_pid_string
322 // REQUIRES: lock_ is held
323 bool CreateLogfile(const string& time_pid_string);
328 class LogDestination {
330 friend class LogMessage;
331 friend void ReprintFatalMessage();
332 friend base::Logger* base::GetLogger(LogSeverity);
333 friend void base::SetLogger(LogSeverity, base::Logger*);
335 // These methods are just forwarded to by their global versions.
336 static void SetLogDestination(LogSeverity severity,
337 const char* base_filename);
338 static void SetLogSymlink(LogSeverity severity,
339 const char* symlink_basename);
340 static void AddLogSink(LogSink *destination);
341 static void RemoveLogSink(LogSink *destination);
342 static void SetLogFilenameExtension(const char* filename_extension);
343 static void SetStderrLogging(LogSeverity min_severity);
344 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
345 static void LogToStderr();
346 // Flush all log files that are at least at the given severity level
347 static void FlushLogFiles(int min_severity);
348 static void FlushLogFilesUnsafe(int min_severity);
350 // we set the maximum size of our packet to be 1400, the logic being
351 // to prevent fragmentation.
352 // Really this number is arbitrary.
353 static const int kNetworkBytes = 1400;
355 static const string& hostname();
357 static void DeleteLogDestinations();
360 LogDestination(LogSeverity severity, const char* base_filename);
361 ~LogDestination() { }
363 // Take a log message of a particular severity and log it to stderr
364 // iff it's of a high enough severity to deserve it.
365 static void MaybeLogToStderr(LogSeverity severity, const char* message,
368 // Take a log message of a particular severity and log it to email
369 // iff it's of a high enough severity to deserve it.
370 static void MaybeLogToEmail(LogSeverity severity, const char* message,
372 // Take a log message of a particular severity and log it to a file
373 // iff the base filename is not "" (which means "don't log to me")
374 static void MaybeLogToLogfile(LogSeverity severity,
376 const char* message, size_t len);
377 // Take a log message of a particular severity and log it to the file
378 // for that severity and also for all files with severity less than
380 static void LogToAllLogfiles(LogSeverity severity,
382 const char* message, size_t len);
384 // Send logging info to all registered sinks.
385 static void LogToSinks(LogSeverity severity,
386 const char *full_filename,
387 const char *base_filename,
389 const struct ::tm* tm_time,
393 // Wait for all registered sinks via WaitTillSent
394 // including the optional one in "data".
395 static void WaitForSinks(LogMessage::LogMessageData* data);
397 static LogDestination* log_destination(LogSeverity severity);
399 LogFileObject fileobject_;
400 base::Logger* logger_; // Either &fileobject_, or wrapper around it
402 static LogDestination* log_destinations_[NUM_SEVERITIES];
403 static LogSeverity email_logging_severity_;
404 static string addresses_;
405 static string hostname_;
407 // arbitrary global logging destinations.
408 static vector<LogSink*>* sinks_;
410 // Protects the vector sinks_,
411 // but not the LogSink objects its elements reference.
412 static Mutex sink_mutex_;
415 LogDestination(const LogDestination&);
416 LogDestination& operator=(const LogDestination&);
419 // Errors do not get logged to email by default.
420 LogSeverity LogDestination::email_logging_severity_ = 99999;
422 string LogDestination::addresses_;
423 string LogDestination::hostname_;
425 vector<LogSink*>* LogDestination::sinks_ = NULL;
426 Mutex LogDestination::sink_mutex_;
429 const string& LogDestination::hostname() {
430 if (hostname_.empty()) {
431 GetHostName(&hostname_);
432 if (hostname_.empty()) {
433 hostname_ = "(unknown)";
439 LogDestination::LogDestination(LogSeverity severity,
440 const char* base_filename)
441 : fileobject_(severity, base_filename),
442 logger_(&fileobject_) {
445 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
446 // assume we have the log_mutex or we simply don't care
448 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
449 LogDestination* log = log_destination(i);
451 // Flush the base fileobject_ logger directly instead of going
452 // through any wrappers to reduce chance of deadlock.
453 log->fileobject_.FlushUnlocked();
458 inline void LogDestination::FlushLogFiles(int min_severity) {
459 // Prevent any subtle race conditions by wrapping a mutex lock around
461 MutexLock l(&log_mutex);
462 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
463 LogDestination* log = log_destination(i);
465 log->logger_->Flush();
470 inline void LogDestination::SetLogDestination(LogSeverity severity,
471 const char* base_filename) {
472 assert(severity >= 0 && severity < NUM_SEVERITIES);
473 // Prevent any subtle race conditions by wrapping a mutex lock around
475 MutexLock l(&log_mutex);
476 log_destination(severity)->fileobject_.SetBasename(base_filename);
479 inline void LogDestination::SetLogSymlink(LogSeverity severity,
480 const char* symlink_basename) {
481 CHECK_GE(severity, 0);
482 CHECK_LT(severity, NUM_SEVERITIES);
483 MutexLock l(&log_mutex);
484 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
487 inline void LogDestination::AddLogSink(LogSink *destination) {
488 // Prevent any subtle race conditions by wrapping a mutex lock around
490 MutexLock l(&sink_mutex_);
491 if (!sinks_) sinks_ = new vector<LogSink*>;
492 sinks_->push_back(destination);
495 inline void LogDestination::RemoveLogSink(LogSink *destination) {
496 // Prevent any subtle race conditions by wrapping a mutex lock around
498 MutexLock l(&sink_mutex_);
499 // This doesn't keep the sinks in order, but who cares?
501 for (int i = sinks_->size() - 1; i >= 0; i--) {
502 if ((*sinks_)[i] == destination) {
503 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
511 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
512 // Prevent any subtle race conditions by wrapping a mutex lock around
514 MutexLock l(&log_mutex);
515 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
516 log_destination(severity)->fileobject_.SetExtension(ext);
520 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
521 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
522 // Prevent any subtle race conditions by wrapping a mutex lock around
524 MutexLock l(&log_mutex);
525 FLAGS_stderrthreshold = min_severity;
528 inline void LogDestination::LogToStderr() {
529 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
530 // SetLogDestination already do the locking!
531 SetStderrLogging(0); // thus everything is "also" logged to stderr
532 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
533 SetLogDestination(i, ""); // "" turns off logging to a logfile
537 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
538 const char* addresses) {
539 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
540 // Prevent any subtle race conditions by wrapping a mutex lock around
542 MutexLock l(&log_mutex);
543 LogDestination::email_logging_severity_ = min_severity;
544 LogDestination::addresses_ = addresses;
547 static void WriteToStderr(const char* message, size_t len) {
548 // Avoid using cerr from this module since we may get called during
549 // exit code, and cerr may be partially or fully destroyed by then.
550 fwrite(message, len, 1, stderr);
553 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
554 const char* message, size_t len) {
555 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
556 WriteToStderr(message, len);
558 // On Windows, also output to the debugger
559 ::OutputDebugStringA(string(message,len).c_str());
565 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
566 const char* message, size_t len) {
567 if (severity >= email_logging_severity_ ||
568 severity >= FLAGS_logemaillevel) {
569 string to(FLAGS_alsologtoemail);
570 if (!addresses_.empty()) {
576 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
577 glog_internal_namespace_::ProgramInvocationShortName());
578 string body(hostname());
580 body.append(message, len);
582 // should NOT use SendEmail(). The caller of this function holds the
583 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
584 // acquire the log_mutex object. Use SendEmailInternal() and set
585 // use_logging to false.
586 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
591 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
595 const bool should_flush = severity > FLAGS_logbuflevel;
596 LogDestination* destination = log_destination(severity);
597 destination->logger_->Write(should_flush, timestamp, message, len);
600 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
605 if ( FLAGS_logtostderr ) // global flag: never log to file
606 WriteToStderr(message, len);
608 for (int i = severity; i >= 0; --i)
609 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
613 inline void LogDestination::LogToSinks(LogSeverity severity,
614 const char *full_filename,
615 const char *base_filename,
617 const struct ::tm* tm_time,
619 size_t message_len) {
620 ReaderMutexLock l(&sink_mutex_);
622 for (int i = sinks_->size() - 1; i >= 0; i--) {
623 (*sinks_)[i]->send(severity, full_filename, base_filename,
624 line, tm_time, message, message_len);
629 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
630 ReaderMutexLock l(&sink_mutex_);
632 for (int i = sinks_->size() - 1; i >= 0; i--) {
633 (*sinks_)[i]->WaitTillSent();
636 const bool send_to_sink =
637 (data->send_method_ == &LogMessage::SendToSink) ||
638 (data->send_method_ == &LogMessage::SendToSinkAndLog);
639 if (send_to_sink && data->sink_ != NULL) {
640 data->sink_->WaitTillSent();
644 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
646 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
647 assert(severity >=0 && severity < NUM_SEVERITIES);
648 if (!log_destinations_[severity]) {
649 log_destinations_[severity] = new LogDestination(severity, NULL);
651 return log_destinations_[severity];
654 void LogDestination::DeleteLogDestinations() {
655 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
656 delete log_destinations_[severity];
657 log_destinations_[severity] = NULL;
663 LogFileObject::LogFileObject(LogSeverity severity,
664 const char* base_filename)
665 : base_filename_selected_(base_filename != NULL),
666 base_filename_((base_filename != NULL) ? base_filename : ""),
667 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
668 filename_extension_(),
671 bytes_since_flush_(0),
673 rollover_attempt_(kRolloverAttemptFrequency-1),
674 next_flush_time_(0) {
675 assert(severity >= 0);
676 assert(severity < NUM_SEVERITIES);
679 LogFileObject::~LogFileObject() {
687 void LogFileObject::SetBasename(const char* basename) {
689 base_filename_selected_ = true;
690 if (base_filename_ != basename) {
691 // Get rid of old log file since we are changing names
695 rollover_attempt_ = kRolloverAttemptFrequency-1;
697 base_filename_ = basename;
701 void LogFileObject::SetExtension(const char* ext) {
703 if (filename_extension_ != ext) {
704 // Get rid of old log file since we are changing names
708 rollover_attempt_ = kRolloverAttemptFrequency-1;
710 filename_extension_ = ext;
714 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
716 symlink_basename_ = symlink_basename;
719 void LogFileObject::Flush() {
724 void LogFileObject::FlushUnlocked(){
727 bytes_since_flush_ = 0;
729 // Figure out when we are due for another flush.
730 const int64 next = (FLAGS_logbufsecs
731 * static_cast<int64>(1000000)); // in usec
732 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
735 bool LogFileObject::CreateLogfile(const string& time_pid_string) {
736 string string_filename = base_filename_+filename_extension_+
738 const char* filename = string_filename.c_str();
739 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
740 if (fd == -1) return false;
742 // Mark the file close-on-exec. We don't really care if this fails
743 fcntl(fd, F_SETFD, FD_CLOEXEC);
746 file_ = fdopen(fd, "a"); // Make a FILE*.
747 if (file_ == NULL) { // Man, we're screwed!
749 unlink(filename); // Erase the half-baked evidence: an unusable log file
753 // We try to create a symlink called <program_name>.<severity>,
754 // which is easier to use. (Every time we create a new logfile,
755 // we destroy the old symlink and create a new one, so it always
756 // points to the latest logfile.) If it fails, we're sad but it's
758 if (!symlink_basename_.empty()) {
759 // take directory from filename
760 const char* slash = strrchr(filename, PATH_SEPARATOR);
761 const string linkname =
762 symlink_basename_ + '.' + LogSeverityNames[severity_];
764 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
765 linkpath += linkname;
766 unlink(linkpath.c_str()); // delete old one if it exists
768 // We must have unistd.h.
770 // Make the symlink be relative (in the same dir) so that if the
771 // entire log directory gets relocated the link is still valid.
772 const char *linkdest = slash ? (slash + 1) : filename;
773 if (symlink(linkdest, linkpath.c_str()) != 0) {
774 // silently ignore failures
777 // Make an additional link to the log file in a place specified by
778 // FLAGS_log_link, if indicated
779 if (!FLAGS_log_link.empty()) {
780 linkpath = FLAGS_log_link + "/" + linkname;
781 unlink(linkpath.c_str()); // delete old one if it exists
782 if (symlink(filename, linkpath.c_str()) != 0) {
783 // silently ignore failures
789 return true; // Everything worked
792 void LogFileObject::Write(bool force_flush,
798 // We don't log if the base_name_ is "" (which means "don't write")
799 if (base_filename_selected_ && base_filename_.empty()) {
803 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
805 if (file_ != NULL) fclose(file_);
807 file_length_ = bytes_since_flush_ = 0;
808 rollover_attempt_ = kRolloverAttemptFrequency-1;
811 // If there's no destination file, make one before outputting
813 // Try to rollover the log file every 32 log messages. The only time
814 // this could matter would be when we have trouble creating the log
815 // file. If that happens, we'll lose lots of log messages, of course!
816 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
817 rollover_attempt_ = 0;
820 localtime_r(×tamp, &tm_time);
822 // The logfile's filename will have the date/time & pid in it
823 ostringstream time_pid_stream;
824 time_pid_stream.fill('0');
825 time_pid_stream << 1900+tm_time.tm_year
826 << setw(2) << 1+tm_time.tm_mon
827 << setw(2) << tm_time.tm_mday
829 << setw(2) << tm_time.tm_hour
830 << setw(2) << tm_time.tm_min
831 << setw(2) << tm_time.tm_sec
833 << GetMainThreadPid();
834 const string& time_pid_string = time_pid_stream.str();
836 if (base_filename_selected_) {
837 if (!CreateLogfile(time_pid_string)) {
838 perror("Could not create log file");
839 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
840 time_pid_string.c_str());
844 // If no base filename for logs of this severity has been set, use a
845 // default base filename of
846 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
847 // logfiles will have names like
848 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
849 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
850 // and 4354 is the pid of the logging process. The date & time reflect
851 // when the file was created for output.
853 // Where does the file get put? Successively try the directories
855 string stripped_filename(
856 glog_internal_namespace_::ProgramInvocationShortName());
858 GetHostName(&hostname);
860 string uidname = MyUserName();
861 // We should not call CHECK() here because this function can be
862 // called after holding on to log_mutex. We don't want to
863 // attempt to hold on to the same mutex, and get into a
864 // deadlock. Simply use a name like invalid-user.
865 if (uidname.empty()) uidname = "invalid-user";
867 stripped_filename = stripped_filename+'.'+hostname+'.'
869 +LogSeverityNames[severity_]+'.';
870 // We're going to (potentially) try to put logs in several different dirs
871 const vector<string> & log_dirs = GetLoggingDirectories();
873 // Go through the list of dirs, and try to create the log file in each
874 // until we succeed or run out of options
875 bool success = false;
876 for (vector<string>::const_iterator dir = log_dirs.begin();
877 dir != log_dirs.end();
879 base_filename_ = *dir + "/" + stripped_filename;
880 if ( CreateLogfile(time_pid_string) ) {
885 // If we never succeeded, we have to give up
886 if ( success == false ) {
887 perror("Could not create logging file");
888 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
889 time_pid_string.c_str());
894 // Write a header message into the log file
895 ostringstream file_header_stream;
896 file_header_stream.fill('0');
897 file_header_stream << "Log file created at: "
898 << 1900+tm_time.tm_year << '/'
899 << setw(2) << 1+tm_time.tm_mon << '/'
900 << setw(2) << tm_time.tm_mday
902 << setw(2) << tm_time.tm_hour << ':'
903 << setw(2) << tm_time.tm_min << ':'
904 << setw(2) << tm_time.tm_sec << '\n'
905 << "Running on machine: "
906 << LogDestination::hostname() << '\n'
907 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
908 << "threadid file:line] msg" << '\n';
909 const string& file_header_string = file_header_stream.str();
911 const int header_len = file_header_string.size();
912 fwrite(file_header_string.data(), 1, header_len, file_);
913 file_length_ += header_len;
914 bytes_since_flush_ += header_len;
918 if ( !stop_writing ) {
919 // fwrite() doesn't return an error when the disk is full, for
920 // messages that are less than 4096 bytes. When the disk is full,
921 // it returns the message length for messages that are less than
922 // 4096 bytes. fwrite() returns 4096 for message lengths that are
923 // greater than 4096, thereby indicating an error.
925 fwrite(message, 1, message_len, file_);
926 if ( FLAGS_stop_logging_if_full_disk &&
927 errno == ENOSPC ) { // disk full, stop writing to disk
928 stop_writing = true; // until the disk is
931 file_length_ += message_len;
932 bytes_since_flush_ += message_len;
935 if ( CycleClock_Now() >= next_flush_time_ )
936 stop_writing = false; // check to see if disk has free space.
937 return; // no need to flush
940 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
941 // or every "FLAGS_logbufsecs" seconds.
943 (bytes_since_flush_ >= 1000000) ||
944 (CycleClock_Now() >= next_flush_time_) ) {
947 if (FLAGS_drop_log_memory) {
948 if (file_length_ >= logging::kPageSize) {
949 // don't evict the most recent page
950 uint32 len = file_length_ & ~(logging::kPageSize - 1);
951 posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
960 // An arbitrary limit on the length of a single log message. This
961 // is so that streaming can be done more efficiently.
962 const size_t LogMessage::kMaxLogMessageLen = 30000;
964 // Static log data space to avoid alloc failures in a LOG(FATAL)
966 // Since multiple threads may call LOG(FATAL), and we want to preserve
967 // the data from the first call, we allocate two sets of space. One
968 // for exclusive use by the first thread, and one for shared use by
969 // all other threads.
970 static Mutex fatal_msg_lock;
971 static CrashReason crash_reason;
972 static bool fatal_msg_exclusive = true;
973 static char fatal_msg_buf_exclusive[LogMessage::kMaxLogMessageLen+1];
974 static char fatal_msg_buf_shared[LogMessage::kMaxLogMessageLen+1];
975 static LogMessage::LogStream fatal_msg_stream_exclusive(
976 fatal_msg_buf_exclusive, LogMessage::kMaxLogMessageLen, 0);
977 static LogMessage::LogStream fatal_msg_stream_shared(
978 fatal_msg_buf_shared, LogMessage::kMaxLogMessageLen, 0);
979 static LogMessage::LogMessageData fatal_msg_data_exclusive;
980 static LogMessage::LogMessageData fatal_msg_data_shared;
982 LogMessage::LogMessageData::~LogMessageData() {
984 delete stream_alloc_;
987 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
988 int ctr, void (LogMessage::*send_method)())
990 Init(file, line, severity, send_method);
991 data_->stream_->set_ctr(ctr);
994 LogMessage::LogMessage(const char* file, int line,
995 const CheckOpString& result)
997 Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
998 stream() << "Check failed: " << (*result.str_) << " ";
1001 LogMessage::LogMessage(const char* file, int line)
1002 : allocated_(NULL) {
1003 Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
1006 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
1007 : allocated_(NULL) {
1008 Init(file, line, severity, &LogMessage::SendToLog);
1011 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1012 LogSink* sink, bool also_send_to_log)
1013 : allocated_(NULL) {
1014 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
1015 &LogMessage::SendToSink);
1016 data_->sink_ = sink; // override Init()'s setting to NULL
1019 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1020 vector<string> *outvec)
1021 : allocated_(NULL) {
1022 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
1023 data_->outvec_ = outvec; // override Init()'s setting to NULL
1026 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1028 : allocated_(NULL) {
1029 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
1030 data_->message_ = message; // override Init()'s setting to NULL
1033 void LogMessage::Init(const char* file,
1035 LogSeverity severity,
1036 void (LogMessage::*send_method)()) {
1038 if (severity != GLOG_FATAL || !exit_on_dfatal) {
1039 allocated_ = new LogMessageData();
1041 data_->buf_ = new char[kMaxLogMessageLen+1];
1042 data_->message_text_ = data_->buf_;
1043 data_->stream_alloc_ =
1044 new LogStream(data_->message_text_, kMaxLogMessageLen, 0);
1045 data_->stream_ = data_->stream_alloc_;
1046 data_->first_fatal_ = false;
1048 MutexLock l(&fatal_msg_lock);
1049 if (fatal_msg_exclusive) {
1050 fatal_msg_exclusive = false;
1051 data_ = &fatal_msg_data_exclusive;
1052 data_->message_text_ = fatal_msg_buf_exclusive;
1053 data_->stream_ = &fatal_msg_stream_exclusive;
1054 data_->first_fatal_ = true;
1056 data_ = &fatal_msg_data_shared;
1057 data_->message_text_ = fatal_msg_buf_shared;
1058 data_->stream_ = &fatal_msg_stream_shared;
1059 data_->first_fatal_ = false;
1061 data_->stream_alloc_ = NULL;
1065 data_->preserved_errno_ = errno;
1066 data_->severity_ = severity;
1067 data_->line_ = line;
1068 data_->send_method_ = send_method;
1069 data_->sink_ = NULL;
1070 data_->outvec_ = NULL;
1071 WallTime now = WallTime_Now();
1072 data_->timestamp_ = static_cast<time_t>(now);
1073 localtime_r(&data_->timestamp_, &data_->tm_time_);
1074 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1075 RawLog__SetLastTime(data_->tm_time_, usecs);
1077 data_->num_chars_to_log_ = 0;
1078 data_->num_chars_to_syslog_ = 0;
1079 data_->basename_ = const_basename(file);
1080 data_->fullname_ = file;
1081 data_->has_been_flushed_ = false;
1083 // If specified, prepend a prefix to each line. For example:
1084 // I1018 160715 f5d4fbb0 logging.cc:1153]
1085 // (log level, GMT month, date, time, thread_id, file basename, line)
1086 // We exclude the thread_id for the default thread.
1087 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1088 stream() << LogSeverityNames[severity][0]
1089 << setw(2) << 1+data_->tm_time_.tm_mon
1090 << setw(2) << data_->tm_time_.tm_mday
1092 << setw(2) << data_->tm_time_.tm_hour << ':'
1093 << setw(2) << data_->tm_time_.tm_min << ':'
1094 << setw(2) << data_->tm_time_.tm_sec << "."
1097 << setfill(' ') << setw(5)
1098 << static_cast<unsigned int>(GetTID()) << setfill('0')
1100 << data_->basename_ << ':' << data_->line_ << "] ";
1102 data_->num_prefix_chars_ = data_->stream_->pcount();
1104 if (!FLAGS_log_backtrace_at.empty()) {
1106 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1107 #ifdef HAVE_STACKTRACE
1108 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1110 DumpStackTraceToString(&stacktrace);
1111 stream() << " (stacktrace:\n" << stacktrace << ") ";
1117 LogMessage::~LogMessage() {
1122 int LogMessage::preserved_errno() const {
1123 return data_->preserved_errno_;
1126 ostream& LogMessage::stream() {
1127 return *(data_->stream_);
1130 // Flush buffered message, called by the destructor, or any other function
1131 // that needs to synchronize the log.
1132 void LogMessage::Flush() {
1133 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1136 data_->num_chars_to_log_ = data_->stream_->pcount();
1137 data_->num_chars_to_syslog_ =
1138 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1140 // Do we need to add a \n to the end of this message?
1141 bool append_newline =
1142 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1143 char original_final_char = '\0';
1145 // If we do need to add a \n, we'll do it by violating the memory of the
1146 // ostrstream buffer. This is quick, and we'll make sure to undo our
1147 // modification before anything else is done with the ostrstream. It
1148 // would be preferable not to do things this way, but it seems to be
1149 // the best way to deal with this.
1150 if (append_newline) {
1151 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1152 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1155 // Prevent any subtle race conditions by wrapping a mutex lock around
1156 // the actual logging action per se.
1158 MutexLock l(&log_mutex);
1159 (this->*(data_->send_method_))();
1160 ++num_messages_[static_cast<int>(data_->severity_)];
1162 LogDestination::WaitForSinks(data_);
1164 if (append_newline) {
1165 // Fix the ostrstream back how it was before we screwed with it.
1166 // It's 99.44% certain that we don't need to worry about doing this.
1167 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1170 // If errno was already set before we enter the logging call, we'll
1171 // set it back to that value when we return from the logging call.
1172 // It happens often that we log an error message after a syscall
1173 // failure, which can potentially set the errno to some other
1174 // values. We would like to preserve the original errno.
1175 if (data_->preserved_errno_ != 0) {
1176 errno = data_->preserved_errno_;
1179 // Note that this message is now safely logged. If we're asked to flush
1180 // again, as a result of destruction, say, we'll do nothing on future calls.
1181 data_->has_been_flushed_ = true;
1184 // Copy of first FATAL log message so that we can print it out again
1185 // after all the stack traces. To preserve legacy behavior, we don't
1186 // use fatal_msg_buf_exclusive.
1187 static time_t fatal_time;
1188 static char fatal_message[256];
1190 void ReprintFatalMessage() {
1191 if (fatal_message[0]) {
1192 const int n = strlen(fatal_message);
1193 if (!FLAGS_logtostderr) {
1194 // Also write to stderr
1195 WriteToStderr(fatal_message, n);
1197 LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1201 // L >= log_mutex (callers must hold the log_mutex).
1202 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1203 static bool already_warned_before_initgoogle = false;
1205 log_mutex.AssertHeld();
1207 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1208 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1210 // Messages of a given severity get logged to lower severity logs, too
1212 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1213 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1214 "written to STDERR\n";
1215 WriteToStderr(w, strlen(w));
1216 already_warned_before_initgoogle = true;
1219 // global flag: never log to file if set. Also -- don't log to a
1220 // file if we haven't parsed the command line flags to get the
1222 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1223 WriteToStderr(data_->message_text_, data_->num_chars_to_log_);
1225 // this could be protected by a flag if necessary.
1226 LogDestination::LogToSinks(data_->severity_,
1227 data_->fullname_, data_->basename_,
1228 data_->line_, &data_->tm_time_,
1229 data_->message_text_ + data_->num_prefix_chars_,
1230 (data_->num_chars_to_log_ -
1231 data_->num_prefix_chars_ - 1));
1234 // log this message to all log files of severity <= severity_
1235 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1236 data_->message_text_,
1237 data_->num_chars_to_log_);
1239 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1240 data_->num_chars_to_log_);
1241 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1242 data_->num_chars_to_log_);
1243 LogDestination::LogToSinks(data_->severity_,
1244 data_->fullname_, data_->basename_,
1245 data_->line_, &data_->tm_time_,
1246 data_->message_text_ + data_->num_prefix_chars_,
1247 (data_->num_chars_to_log_
1248 - data_->num_prefix_chars_ - 1));
1249 // NOTE: -1 removes trailing \n
1252 // If we log a FATAL message, flush all the log destinations, then toss
1253 // a signal for others to catch. We leave the logs in a state that
1254 // someone else can use them (as long as they flush afterwards)
1255 if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1256 if (data_->first_fatal_) {
1257 // Store crash information so that it is accessible from within signal
1258 // handlers that may be invoked later.
1259 RecordCrashReason(&crash_reason);
1260 SetCrashReason(&crash_reason);
1262 // Store shortened fatal message for other logs and GWQ status
1263 const int copy = min<int>(data_->num_chars_to_log_,
1264 sizeof(fatal_message)-1);
1265 memcpy(fatal_message, data_->message_text_, copy);
1266 fatal_message[copy] = '\0';
1267 fatal_time = data_->timestamp_;
1270 if (!FLAGS_logtostderr) {
1271 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1272 if ( LogDestination::log_destinations_[i] )
1273 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1277 // release the lock that our caller (directly or indirectly)
1278 // LogMessage::~LogMessage() grabbed so that signal handlers
1279 // can use the logging facility. Alternately, we could add
1280 // an entire unsafe logging interface to bypass locking
1281 // for signal handlers but this seems simpler.
1283 LogDestination::WaitForSinks(data_);
1285 const char* message = "*** Check failure stack trace: ***\n";
1286 if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1293 void LogMessage::RecordCrashReason(
1294 glog_internal_namespace_::CrashReason* reason) {
1295 reason->filename = fatal_msg_data_exclusive.fullname_;
1296 reason->line_number = fatal_msg_data_exclusive.line_;
1297 reason->message = fatal_msg_buf_exclusive +
1298 fatal_msg_data_exclusive.num_prefix_chars_;
1299 #ifdef HAVE_STACKTRACE
1300 // Retrieve the stack trace, omitting the logging frames that got us here.
1301 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1307 #ifdef HAVE___ATTRIBUTE__
1308 # define ATTRIBUTE_NORETURN __attribute__((noreturn))
1310 # define ATTRIBUTE_NORETURN
1313 static void logging_fail() ATTRIBUTE_NORETURN;
1315 static void logging_fail() {
1316 #if defined(_DEBUG) && defined(_MSC_VER)
1317 // When debugging on windows, avoid the obnoxious dialog and make
1318 // it possible to continue past a LOG(FATAL) in the debugger
1325 typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN;
1327 GOOGLE_GLOG_DLL_DECL
1328 logging_fail_func_t g_logging_fail_func = &logging_fail;
1330 void InstallFailureFunction(void (*fail_func)()) {
1331 g_logging_fail_func = (logging_fail_func_t)fail_func;
1334 void LogMessage::Fail() {
1335 g_logging_fail_func();
1338 // L >= log_mutex (callers must hold the log_mutex).
1339 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1340 if (data_->sink_ != NULL) {
1341 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1342 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1343 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1344 data_->line_, &data_->tm_time_,
1345 data_->message_text_ + data_->num_prefix_chars_,
1346 (data_->num_chars_to_log_ -
1347 data_->num_prefix_chars_ - 1));
1351 // L >= log_mutex (callers must hold the log_mutex).
1352 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1357 // L >= log_mutex (callers must hold the log_mutex).
1358 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1359 if (data_->outvec_ != NULL) {
1360 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1361 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1362 // Omit prefix of message and trailing newline when recording in outvec_.
1363 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1364 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1365 data_->outvec_->push_back(string(start, len));
1371 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1372 if (data_->message_ != NULL) {
1373 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1374 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1375 // Omit prefix of message and trailing newline when writing to message_.
1376 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1377 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1378 data_->message_->assign(start, len);
1383 // L >= log_mutex (callers must hold the log_mutex).
1384 void LogMessage::SendToSyslogAndLog() {
1385 #ifdef HAVE_SYSLOG_H
1386 // Before any calls to syslog(), make a single call to openlog()
1387 static bool openlog_already_called = false;
1388 if (!openlog_already_called) {
1389 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1390 LOG_CONS | LOG_NDELAY | LOG_PID,
1392 openlog_already_called = true;
1395 // This array maps Google severity levels to syslog levels
1396 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1397 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1398 int(data_->num_chars_to_syslog_),
1399 data_->message_text_ + data_->num_prefix_chars_);
1402 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1406 base::Logger* base::GetLogger(LogSeverity severity) {
1407 MutexLock l(&log_mutex);
1408 return LogDestination::log_destination(severity)->logger_;
1411 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1412 MutexLock l(&log_mutex);
1413 LogDestination::log_destination(severity)->logger_ = logger;
1416 // L < log_mutex. Acquires and releases mutex_.
1417 int64 LogMessage::num_messages(int severity) {
1418 MutexLock l(&log_mutex);
1419 return num_messages_[severity];
1422 // Output the COUNTER value. This is only valid if ostream is a
1424 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1426 LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
1428 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1430 CHECK(log && log == log->self())
1431 << "You must not use COUNTER with non-glog ostream";
1436 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1437 LogSeverity severity, int ctr,
1438 void (LogMessage::*send_method)())
1439 : LogMessage(file, line, severity, ctr, send_method) {
1442 ErrnoLogMessage::~ErrnoLogMessage() {
1443 // Don't access errno directly because it may have been altered
1444 // while streaming the message.
1446 posix_strerror_r(preserved_errno(), buf, sizeof(buf));
1447 stream() << ": " << buf << " [" << preserved_errno() << "]";
1450 void FlushLogFiles(LogSeverity min_severity) {
1451 LogDestination::FlushLogFiles(min_severity);
1454 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1455 LogDestination::FlushLogFilesUnsafe(min_severity);
1458 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1459 LogDestination::SetLogDestination(severity, base_filename);
1462 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1463 LogDestination::SetLogSymlink(severity, symlink_basename);
1466 LogSink::~LogSink() {
1469 void LogSink::WaitTillSent() {
1473 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1474 const struct ::tm* tm_time,
1475 const char* message, size_t message_len) {
1476 ostringstream stream(string(message, message_len));
1479 // FIXME(jrvb): Updating this to use the correct value for usecs
1480 // requires changing the signature for both this method and
1481 // LogSink::send(). This change needs to be done in a separate CL
1482 // so subclasses of LogSink can be updated at the same time.
1485 stream << LogSeverityNames[severity][0]
1486 << setw(2) << 1+tm_time->tm_mon
1487 << setw(2) << tm_time->tm_mday
1489 << setw(2) << tm_time->tm_hour << ':'
1490 << setw(2) << tm_time->tm_min << ':'
1491 << setw(2) << tm_time->tm_sec << '.'
1494 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1496 << file << ':' << line << "] ";
1498 stream << string(message, message_len);
1499 return stream.str();
1502 void AddLogSink(LogSink *destination) {
1503 LogDestination::AddLogSink(destination);
1506 void RemoveLogSink(LogSink *destination) {
1507 LogDestination::RemoveLogSink(destination);
1510 void SetLogFilenameExtension(const char* ext) {
1511 LogDestination::SetLogFilenameExtension(ext);
1514 void SetStderrLogging(LogSeverity min_severity) {
1515 LogDestination::SetStderrLogging(min_severity);
1518 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1519 LogDestination::SetEmailLogging(min_severity, addresses);
1522 void LogToStderr() {
1523 LogDestination::LogToStderr();
1527 namespace internal {
1529 bool GetExitOnDFatal() {
1530 MutexLock l(&log_mutex);
1531 return exit_on_dfatal;
1534 // Determines whether we exit the program for a LOG(DFATAL) message in
1535 // debug mode. It does this by skipping the call to Fail/FailQuietly.
1536 // This is intended for testing only.
1538 // This can have some effects on LOG(FATAL) as well. Failure messages
1539 // are always allocated (rather than sharing a buffer), the crash
1540 // reason is not recorded, the "gwq" status message is not updated,
1541 // and the stack trace is not recorded. The LOG(FATAL) *will* still
1542 // exit the program. Since this function is used only in testing,
1543 // these differences are acceptable.
1544 void SetExitOnDFatal(bool value) {
1545 MutexLock l(&log_mutex);
1546 exit_on_dfatal = value;
1549 } // namespace internal
1552 // use_logging controls whether the logging functions LOG/VLOG are used
1553 // to log errors. It should be set to false when the caller holds the
1555 static bool SendEmailInternal(const char*dest, const char *subject,
1556 const char*body, bool use_logging) {
1557 if (dest && *dest) {
1558 if ( use_logging ) {
1559 VLOG(1) << "Trying to send TITLE:" << subject
1560 << " BODY:" << body << " to " << dest;
1562 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1563 subject, body, dest);
1567 FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1568 FILE* pipe = popen(cmd.c_str(), "w");
1570 // Add the body if we have one
1572 fwrite(body, sizeof(char), strlen(body), pipe);
1573 bool ok = pclose(pipe) != -1;
1575 if ( use_logging ) {
1577 posix_strerror_r(errno, buf, sizeof(buf));
1578 LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf;
1581 posix_strerror_r(errno, buf, sizeof(buf));
1582 fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf);
1587 if ( use_logging ) {
1588 LOG(ERROR) << "Unable to send mail to " << dest;
1590 fprintf(stderr, "Unable to send mail to %s\n", dest);
1597 bool SendEmail(const char*dest, const char *subject, const char*body){
1598 return SendEmailInternal(dest, subject, body, true);
1601 static void GetTempDirectories(vector<string>* list) {
1604 // On windows we'll try to find a directory in this order:
1605 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1608 // C:/WINDOWS/ or C:/WINNT/
1611 if (GetTempPathA(MAX_PATH, tmp))
1612 list->push_back(tmp);
1613 list->push_back("C:\\tmp\\");
1614 list->push_back("C:\\temp\\");
1616 // Directories, in order of preference. If we find a dir that
1617 // exists, we stop adding other less-preferred dirs
1618 const char * candidates[] = {
1619 // Non-null only during unittest/regtest
1620 getenv("TEST_TMPDIR"),
1622 // Explicitly-supplied temp dirs
1623 getenv("TMPDIR"), getenv("TMP"),
1625 // If all else fails
1629 for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
1630 const char *d = candidates[i];
1631 if (!d) continue; // Empty env var
1633 // Make sure we don't surprise anyone who's expecting a '/'
1635 if (dstr[dstr.size() - 1] != '/') {
1638 list->push_back(dstr);
1640 struct stat statbuf;
1641 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1642 // We found a dir that exists - we're done.
1650 static vector<string>* logging_directories_list;
1652 const vector<string>& GetLoggingDirectories() {
1653 // Not strictly thread-safe but we're called early in InitGoogle().
1654 if (logging_directories_list == NULL) {
1655 logging_directories_list = new vector<string>;
1657 if ( !FLAGS_log_dir.empty() ) {
1658 // A dir was specified, we should use it
1659 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1661 GetTempDirectories(logging_directories_list);
1664 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1665 logging_directories_list->push_back(tmp);
1666 logging_directories_list->push_back(".\\");
1668 logging_directories_list->push_back("./");
1672 return *logging_directories_list;
1675 void TestOnly_ClearLoggingDirectoriesList() {
1676 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1677 "called from test code.\n");
1678 delete logging_directories_list;
1679 logging_directories_list = NULL;
1682 void GetExistingTempDirectories(vector<string>* list) {
1683 GetTempDirectories(list);
1684 vector<string>::iterator i_dir = list->begin();
1685 while( i_dir != list->end() ) {
1686 // zero arg to access means test for existence; no constant
1687 // defined on windows
1688 if ( access(i_dir->c_str(), 0) ) {
1689 i_dir = list->erase(i_dir);
1696 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1697 #ifdef HAVE_UNISTD_H
1698 struct stat statbuf;
1699 const int kCopyBlockSize = 8 << 10;
1700 char copybuf[kCopyBlockSize];
1701 int64 read_offset, write_offset;
1702 // Don't follow symlinks unless they're our own fd symlinks in /proc
1704 const char *procfd_prefix = "/proc/self/fd/";
1705 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1707 int fd = open(path, flags);
1709 if (errno == EFBIG) {
1710 // The log file in question has got too big for us to open. The
1711 // real fix for this would be to compile logging.cc (or probably
1712 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1714 // Instead just truncate the file to something we can manage
1715 if (truncate(path, 0) == -1) {
1716 PLOG(ERROR) << "Unable to truncate " << path;
1718 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1721 PLOG(ERROR) << "Unable to open " << path;
1726 if (fstat(fd, &statbuf) == -1) {
1727 PLOG(ERROR) << "Unable to fstat()";
1731 // See if the path refers to a regular file bigger than the
1733 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1734 if (statbuf.st_size <= limit) goto out_close_fd;
1735 if (statbuf.st_size <= keep) goto out_close_fd;
1737 // This log file is too large - we need to truncate it
1738 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1740 // Copy the last "keep" bytes of the file to the beginning of the file
1741 read_offset = statbuf.st_size - keep;
1743 int bytesin, bytesout;
1744 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1745 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1746 if (bytesout == -1) {
1747 PLOG(ERROR) << "Unable to write to " << path;
1749 } else if (bytesout != bytesin) {
1750 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1752 read_offset += bytesin;
1753 write_offset += bytesout;
1755 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1757 // Truncate the remainder of the file. If someone else writes to the
1758 // end of the file after our last read() above, we lose their latest
1759 // data. Too bad ...
1760 if (ftruncate(fd, write_offset) == -1) {
1761 PLOG(ERROR) << "Unable to truncate " << path;
1767 LOG(ERROR) << "No log truncation support.";
1771 void TruncateStdoutStderr() {
1772 #ifdef HAVE_UNISTD_H
1773 int64 limit = MaxLogSize() << 20;
1774 int64 keep = 1 << 20;
1775 TruncateLogFile("/proc/self/fd/1", limit, keep);
1776 TruncateLogFile("/proc/self/fd/2", limit, keep);
1778 LOG(ERROR) << "No log truncation support.";
1783 // Helper functions for string comparisons.
1784 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1785 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1786 const char* names) { \
1787 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1788 if (equal == expected) return NULL; \
1793 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1794 return new string(ss.str()); \
1797 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1798 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1799 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1800 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1801 #undef DEFINE_CHECK_STROP_IMPL
1803 int posix_strerror_r(int err, char *buf, size_t len) {
1804 // Sanity check input parameters
1805 if (buf == NULL || len <= 0) {
1810 // Reset buf and errno, and try calling whatever version of strerror_r()
1811 // is implemented by glibc
1813 int old_errno = errno;
1815 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1817 // Both versions set errno on failure
1819 // Should already be there, but better safe than sorry
1825 // POSIX is vague about whether the string will be terminated, although
1826 // is indirectly implies that typically ERANGE will be returned, instead
1827 // of truncating the string. This is different from the GNU implementation.
1828 // We play it safe by always terminating the string explicitly.
1829 buf[len-1] = '\000';
1831 // If the function succeeded, we can use its exit code to determine the
1832 // semantics implemented by glibc
1836 // GNU semantics detected
1841 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
1842 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
1843 // This means an error on MacOSX or FreeBSD.
1847 strncat(buf, rc, len-1);
1853 LogMessageFatal::LogMessageFatal(const char* file, int line) :
1854 LogMessage(file, line, GLOG_FATAL) {}
1856 LogMessageFatal::LogMessageFatal(const char* file, int line,
1857 const CheckOpString& result) :
1858 LogMessage(file, line, result) {}
1860 LogMessageFatal::~LogMessageFatal() {
1867 CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
1868 : stream_(new ostringstream) {
1869 *stream_ << exprtext << " (";
1872 CheckOpMessageBuilder::~CheckOpMessageBuilder() {
1876 ostream* CheckOpMessageBuilder::ForVar2() {
1877 *stream_ << " vs. ";
1881 string* CheckOpMessageBuilder::NewString() {
1883 return new string(stream_->str());
1889 void MakeCheckOpValueString(std::ostream* os, const char& v) {
1890 if (v >= 32 && v <= 126) {
1891 (*os) << "'" << v << "'";
1893 (*os) << "char value " << (short)v;
1898 void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
1899 if (v >= 32 && v <= 126) {
1900 (*os) << "'" << v << "'";
1902 (*os) << "signed char value " << (short)v;
1907 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
1908 if (v >= 32 && v <= 126) {
1909 (*os) << "'" << v << "'";
1911 (*os) << "unsigned char value " << (unsigned short)v;
1915 void InitGoogleLogging(const char* argv0) {
1916 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
1919 void ShutdownGoogleLogging() {
1920 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
1921 LogDestination::DeleteLogDestinations();
1922 delete logging_directories_list;
1923 logging_directories_list = NULL;
1926 _END_GOOGLE_NAMESPACE_