1 #define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite()
11 #include <sys/types.h>
13 #include <sys/utsname.h>
22 #include <errno.h> // for errno
24 #include "base/commandlineflags.h" // to get the program name
25 #include "glog/logging.h"
26 #include "glog/raw_logging.h"
27 #include "base/googleinit.h"
31 using std::ostrstream;
37 using std::ostringstream;
40 DEFINE_bool(logtostderr, false,
41 "log messages go to stderr instead of logfiles");
42 DEFINE_bool(alsologtostderr, false,
43 "log messages go to stderr in addition to logfiles");
45 // By default, errors (including fatal errors) get logged to stderr as
48 // The default is ERROR instead of FATAL so that users can see problems
49 // when they run a program without having to look in another file.
50 DEFINE_int32(stderrthreshold,
51 GOOGLE_NAMESPACE::ERROR,
52 "log messages at or above this level are copied to stderr in "
53 "addition to logfiles. This flag obsoletes --alsologtostderr.");
55 DEFINE_string(alsologtoemail, "",
56 "log messages go to these email addresses "
57 "in addition to logfiles");
58 DEFINE_bool(log_prefix, true,
59 "Prepend the log prefix to the start of each log line");
60 DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
61 "actually get logged anywhere");
62 DEFINE_int32(logbuflevel, 0,
63 "Buffer log messages logged at this level or lower"
64 " (-1 means don't buffer; 0 means buffer INFO only;"
66 DEFINE_int32(logbufsecs, 30,
67 "Buffer log messages for at most this many seconds");
68 DEFINE_int32(logemaillevel, 999,
69 "Email log messages logged at this level or higher"
70 " (0 means email all; 3 means email FATAL only;"
72 DEFINE_string(logmailer, "/bin/mail",
73 "Mailer used to send logging email");
75 // Compute the default value for --log_dir
76 static const char* DefaultLogDir() {
78 env = getenv("GOOGLE_LOG_DIR");
79 if (env != NULL && env[0] != '\0') {
82 env = getenv("TEST_TMPDIR");
83 if (env != NULL && env[0] != '\0') {
89 DEFINE_string(log_dir, DefaultLogDir(),
90 "If specified, logfiles are written into this directory instead "
91 "of the default logging directory.");
92 DEFINE_string(log_link, "", "Put additional links to the log "
93 "files in this directory");
95 DEFINE_int32(max_log_size, 1800,
96 "approx. maximum log file size (in MB)");
98 DEFINE_bool(stop_logging_if_full_disk, false,
99 "Stop attempting to log to disk if the disk is full.");
101 // TODO(hamaji): consider windows
102 #define PATH_SEPARATOR '/'
104 _START_GOOGLE_NAMESPACE_
106 // A mutex that allows only one thread to log at a time, to keep things from
107 // getting jumbled. Some other very uncommon logging operations (like
108 // changing the destination file for log messages of a given severity) also
109 // lock this mutex. Please be sure that anybody who might possibly need to
111 static Mutex log_mutex;
113 // Number of messages sent at each severity. Under log_mutex.
114 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
116 // Globally disable log writing (if disk is full)
117 static bool stop_writing = false;
119 const char*const LogSeverityNames[NUM_SEVERITIES] = {
120 "INFO", "WARNING", "ERROR", "FATAL"
123 const char* GetLogSeverityName(LogSeverity severity) {
124 return LogSeverityNames[severity];
127 static bool SendEmailInternal(const char*dest, const char *subject,
128 const char*body, bool use_logging);
130 base::Logger::~Logger() {
133 // Encapsulates all file-system related state
134 class LogFileObject : public base::Logger {
136 LogFileObject(LogSeverity severity, const char* base_filename);
139 virtual void Write(bool force_flush, // Should we force a flush here?
140 time_t timestamp, // Timestamp for this entry
144 // Configuration options
145 void SetBasename(const char* basename);
146 void SetExtension(const char* ext);
147 void SetSymlinkBasename(const char* symlink_basename);
149 // Normal flushing routine
150 virtual void Flush();
152 // It is the actual file length for the system loggers,
153 // i.e., INFO, ERROR, etc.
154 virtual uint32 LogSize() {
159 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
160 // can avoid grabbing a lock. Usually Flush() calls it after
162 void FlushUnlocked();
165 static const uint32 kRolloverAttemptFrequency = 0x20;
168 bool base_filename_selected_;
169 string base_filename_;
170 string symlink_basename_;
171 string filename_extension_; // option users can specify (eg to add port#)
173 LogSeverity severity_;
174 uint32 bytes_since_flush_;
176 unsigned int rollover_attempt_;
177 int64 next_flush_time_; // cycle count at which to flush log
179 // Actually create a logfile using the value of base_filename_ and the
180 // supplied argument time_pid_string
181 // REQUIRES: lock_ is held
182 bool CreateLogfile(const char* time_pid_string);
185 LogFileObject::LogFileObject(LogSeverity severity,
186 const char* base_filename)
187 : base_filename_selected_(base_filename != NULL),
188 base_filename_((base_filename != NULL) ? base_filename : ""),
189 symlink_basename_(ProgramInvocationShortName()),
190 filename_extension_(),
193 bytes_since_flush_(0),
195 rollover_attempt_(kRolloverAttemptFrequency-1),
196 next_flush_time_(0) {
197 assert(severity >= 0);
198 assert(severity < NUM_SEVERITIES);
201 LogFileObject::~LogFileObject() {
209 void LogFileObject::SetBasename(const char* basename) {
211 base_filename_selected_ = true;
212 if (base_filename_ != basename) {
213 // Get rid of old log file since we are changing names
217 rollover_attempt_ = kRolloverAttemptFrequency-1;
219 base_filename_ = basename;
223 void LogFileObject::SetExtension(const char* ext) {
225 if (filename_extension_ != ext) {
226 // Get rid of old log file since we are changing names
230 rollover_attempt_ = kRolloverAttemptFrequency-1;
232 filename_extension_ = ext;
236 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
238 symlink_basename_ = symlink_basename;
241 class LogDestination {
243 friend class LogMessage;
244 friend void ReprintFatalMessage();
245 friend base::Logger* base::GetLogger(LogSeverity);
246 friend void base::SetLogger(LogSeverity, base::Logger*);
248 // These methods are just forwarded to by their global versions.
249 static void SetLogDestination(LogSeverity severity,
250 const char* base_filename);
251 static void SetLogSymlink(LogSeverity severity,
252 const char* symlink_basename);
253 static void AddLogSink(LogSink *destination);
254 static void RemoveLogSink(LogSink *destination);
255 static void SetLogFilenameExtension(const char* filename_extension);
256 static void SetStderrLogging(LogSeverity min_severity);
257 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
258 static void LogToStderr();
259 // Flush all log files that are at least at the given severity level
260 static void FlushLogFiles(int min_severity);
261 static void FlushLogFilesUnsafe(int min_severity);
263 // we set the maximum size of our packet to be 1400, the logic being
264 // to prevent fragmentation.
265 // Really this number is arbitrary.
266 static const int kNetworkBytes = 1400;
268 static const string& hostname();
271 LogDestination(LogSeverity severity, const char* base_filename);
272 ~LogDestination() { }
274 // Take a log message of a particular severity and log it to stderr
275 // iff it's of a high enough severity to deserve it.
276 static void MaybeLogToStderr(LogSeverity severity, const char* message,
279 // Take a log message of a particular severity and log it to email
280 // iff it's of a high enough severity to deserve it.
281 static void MaybeLogToEmail(LogSeverity severity, const char* message,
283 // Take a log message of a particular severity and log it to a file
284 // iff the base filename is not "" (which means "don't log to me")
285 static void MaybeLogToLogfile(LogSeverity severity,
287 const char* message, size_t len);
288 // Take a log message of a particular severity and log it to the file
289 // for that severity and also for all files with severity less than
291 static void LogToAllLogfiles(LogSeverity severity,
293 const char* message, size_t len);
295 // Send logging info to all registered sinks.
296 static void LogToSinks(LogSeverity severity,
297 const char *full_filename,
298 const char *base_filename,
300 const struct ::tm* tm_time,
304 // Wait for all registered sinks via WaitTillSent
305 // including the optional one in "data".
306 static void WaitForSinks(LogMessage::LogMessageData* data);
308 static LogDestination* log_destination(LogSeverity severity);
310 LogFileObject fileobject_;
311 base::Logger* logger_; // Either &fileobject_, or wrapper around it
313 static LogDestination* log_destinations_[NUM_SEVERITIES];
314 static LogSeverity email_logging_severity_;
315 static string addresses_;
316 static string hostname_;
318 // arbitrary global logging destinations.
319 static vector<LogSink*>* sinks_;
321 // Protects the vector sinks_,
322 // but not the LogSink objects its elements reference.
323 static Mutex sink_mutex_;
326 LogDestination(const LogDestination&);
327 LogDestination& operator=(const LogDestination&);
330 // Errors do not get logged to email by default.
331 LogSeverity LogDestination::email_logging_severity_ = 99999;
333 string LogDestination::addresses_ = "";
334 string LogDestination::hostname_ = "";
336 vector<LogSink*>* LogDestination::sinks_ = NULL;
337 Mutex LogDestination::sink_mutex_;
340 const string& LogDestination::hostname() {
341 if (hostname_.empty()) {
343 if (0 == uname(&buf)) {
344 hostname_ = buf.nodename;
346 hostname_ = "(unknown)";
352 LogDestination::LogDestination(LogSeverity severity,
353 const char* base_filename)
354 : fileobject_(severity, base_filename),
355 logger_(&fileobject_) {
358 void LogFileObject::Flush() {
363 void LogFileObject::FlushUnlocked(){
366 bytes_since_flush_ = 0;
368 // Figure out when we are due for another flush.
369 const int64 next = (FLAGS_logbufsecs
370 * static_cast<int64>(1000000)); // in usec
371 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
374 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
375 // assume we have the log_mutex or we simply don't care
377 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
378 LogDestination* log = log_destination(i);
380 // Flush the base fileobject_ logger directly instead of going
381 // through any wrappers to reduce chance of deadlock.
382 log->fileobject_.FlushUnlocked();
387 inline void LogDestination::FlushLogFiles(int min_severity) {
388 // Prevent any subtle race conditions by wrapping a mutex lock around
390 MutexLock l(&log_mutex);
391 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
392 LogDestination* log = log_destination(i);
394 log->logger_->Flush();
399 inline void LogDestination::SetLogDestination(LogSeverity severity,
400 const char* base_filename) {
401 assert(severity >= 0 && severity < NUM_SEVERITIES);
402 // Prevent any subtle race conditions by wrapping a mutex lock around
404 MutexLock l(&log_mutex);
405 log_destination(severity)->fileobject_.SetBasename(base_filename);
408 inline void LogDestination::SetLogSymlink(LogSeverity severity,
409 const char* symlink_basename) {
410 CHECK_GE(severity, 0);
411 CHECK_LT(severity, NUM_SEVERITIES);
412 MutexLock l(&log_mutex);
413 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
416 inline void LogDestination::AddLogSink(LogSink *destination) {
417 // Prevent any subtle race conditions by wrapping a mutex lock around
419 MutexLock l(&sink_mutex_);
420 if (!sinks_) sinks_ = new vector<LogSink*>;
421 sinks_->push_back(destination);
424 inline void LogDestination::RemoveLogSink(LogSink *destination) {
425 // Prevent any subtle race conditions by wrapping a mutex lock around
427 MutexLock l(&sink_mutex_);
428 // This doesn't keep the sinks in order, but who cares?
430 for (int i = sinks_->size() - 1; i >= 0; i--) {
431 if ((*sinks_)[i] == destination) {
432 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
440 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
441 // Prevent any subtle race conditions by wrapping a mutex lock around
443 MutexLock l(&log_mutex);
444 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
445 log_destination(severity)->fileobject_.SetExtension(ext);
449 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
450 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
451 // Prevent any subtle race conditions by wrapping a mutex lock around
453 MutexLock l(&log_mutex);
454 FLAGS_stderrthreshold = min_severity;
457 inline void LogDestination::LogToStderr() {
458 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
459 // SetLogDestination already do the locking!
460 SetStderrLogging(0); // thus everything is "also" logged to stderr
461 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
462 SetLogDestination(i, ""); // "" turns off logging to a logfile
466 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
467 const char* addresses) {
468 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
469 // Prevent any subtle race conditions by wrapping a mutex lock around
471 MutexLock l(&log_mutex);
472 LogDestination::email_logging_severity_ = min_severity;
473 LogDestination::addresses_ = addresses;
476 static void WriteToStderr(const char* message, size_t len) {
477 // Avoid using cerr from this module since we may get called during
478 // exit code, and cerr may be partially or fully destroyed by then.
479 fwrite(message, len, 1, stderr);
482 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
483 const char* message, size_t len) {
484 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
485 WriteToStderr(message, len);
487 // On Windows, also output to the debugger
488 ::OutputDebugStringA(string(message,len).c_str());
494 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
495 const char* message, size_t len) {
496 if (severity >= email_logging_severity_ ||
497 severity >= FLAGS_logemaillevel) {
498 string to(FLAGS_alsologtoemail);
499 if (!addresses_.empty()) {
505 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
506 ProgramInvocationShortName());
507 string body(hostname());
509 body.append(message, len);
511 // should NOT use SendEmail(). The caller of this function holds the
512 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
513 // acquire the log_mutex object. Use SendEmailInternal() and set
514 // use_logging to false.
515 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
520 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
524 const bool should_flush = severity > FLAGS_logbuflevel;
525 LogDestination* destination = log_destination(severity);
526 destination->logger_->Write(should_flush, timestamp, message, len);
529 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
534 if ( FLAGS_logtostderr ) // global flag: never log to file
535 WriteToStderr(message, len);
537 for (int i = severity; i >= 0; --i)
538 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
542 inline void LogDestination::LogToSinks(LogSeverity severity,
543 const char *full_filename,
544 const char *base_filename,
546 const struct ::tm* tm_time,
548 size_t message_len) {
549 ReaderMutexLock l(&sink_mutex_);
551 for (int i = sinks_->size() - 1; i >= 0; i--) {
552 (*sinks_)[i]->send(severity, full_filename, base_filename,
553 line, tm_time, message, message_len);
558 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
559 ReaderMutexLock l(&sink_mutex_);
561 for (int i = sinks_->size() - 1; i >= 0; i--) {
562 (*sinks_)[i]->WaitTillSent();
565 if (data->send_method_ == &LogMessage::SendToSinkAndLog &&
566 data->sink_ != NULL) {
567 data->sink_->WaitTillSent();
571 bool LogFileObject::CreateLogfile(const char* time_pid_string) {
572 string string_filename = base_filename_+filename_extension_+
574 const char* filename = string_filename.c_str();
575 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
576 if (fd == -1) return false;
577 // Mark the file close-on-exec. We don't really care if this fails
578 fcntl(fd, F_SETFD, FD_CLOEXEC);
580 file_ = fdopen(fd, "a"); // Make a FILE*.
581 if (file_ == NULL) { // Man, we're screwed!
583 unlink(filename); // Erase the half-baked evidence: an unusable log file
587 // We try to create a symlink called <program_name>.<severity>,
588 // which is easier to use. (Every time we create a new logfile,
589 // we destroy the old symlink and create a new one, so it always
590 // points to the latest logfile.) If it fails, we're sad but it's
592 if (!symlink_basename_.empty()) {
593 // take directory from filename
594 const char* slash = strrchr(filename, PATH_SEPARATOR);
595 const string linkname =
596 symlink_basename_ + '.' + LogSeverityNames[severity_];
598 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
599 linkpath += linkname;
600 unlink(linkpath.c_str()); // delete old one if it exists
602 // Make the symlink be relative (in the same dir) so that if the
603 // entire log directory gets relocated the link is still valid.
604 const char *linkdest = slash ? (slash + 1) : filename;
605 symlink(linkdest, linkpath.c_str()); // silently ignore failures
607 // Make an additional link to the log file in a place specified by
608 // FLAGS_log_link, if indicated
609 if (!FLAGS_log_link.empty()) {
610 linkpath = FLAGS_log_link + "/" + linkname;
611 unlink(linkpath.c_str()); // delete old one if it exists
612 symlink(filename, linkpath.c_str()); // silently ignore failures
616 return true; // Everything worked
619 void LogFileObject::Write(bool force_flush,
625 // We don't log if the base_name_ is "" (which means "don't write")
626 if (base_filename_selected_ && base_filename_.empty()) {
630 if ((file_length_ >> 20) >= FLAGS_max_log_size) {
633 file_length_ = bytes_since_flush_ = 0;
634 rollover_attempt_ = kRolloverAttemptFrequency-1;
637 // If there's no destination file, make one before outputting
639 // Try to rollover the log file every 32 log messages. The only time
640 // this could matter would be when we have trouble creating the log
641 // file. If that happens, we'll lose lots of log messages, of course!
642 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
643 rollover_attempt_ = 0;
646 localtime_r(×tamp, &tm_time);
648 // The logfile's filename will have the date/time & pid in it
649 char time_pid_string[256]; // More than enough chars for time, pid, \0
650 ostrstream time_pid_stream(time_pid_string, sizeof(time_pid_string));
651 time_pid_stream.fill('0');
652 time_pid_stream << 1900+tm_time.tm_year
653 << setw(2) << 1+tm_time.tm_mon
654 << setw(2) << tm_time.tm_mday
656 << setw(2) << tm_time.tm_hour
657 << setw(2) << tm_time.tm_min
658 << setw(2) << tm_time.tm_sec
660 << GetMainThreadPid()
663 if (base_filename_selected_) {
664 if (!CreateLogfile(time_pid_string)) {
665 perror("Could not create log file");
666 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", time_pid_string);
670 // If no base filename for logs of this severity has been set, use a
671 // default base filename of
672 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
673 // logfiles will have names like
674 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
675 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
676 // and 4354 is the pid of the logging process. The date & time reflect
677 // when the file was created for output.
679 // Where does the file get put? Successively try the directories
681 string stripped_filename(ProgramInvocationShortName()); // in cmdlineflag
683 if (0 != uname(&buf)) {
684 *buf.nodename = '\0'; // ensure null termination on failure
687 string uidname = MyUserName();
688 // We should not call CHECK() here because this function can be
689 // called after holding on to log_mutex. We don't want to
690 // attempt to hold on to the same mutex, and get into a
691 // deadlock. Simply use a name like invalid-user.
692 if (uidname.empty()) uidname = "invalid-user";
694 stripped_filename = stripped_filename+'.'+buf.nodename+'.'
696 +LogSeverityNames[severity_]+'.';
697 // We're going to (potentially) try to put logs in several different dirs
698 const vector<string> & log_dirs = GetLoggingDirectories();
700 // Go through the list of dirs, and try to create the log file in each
701 // until we succeed or run out of options
702 bool success = false;
703 for (vector<string>::const_iterator dir = log_dirs.begin();
704 dir != log_dirs.end();
706 base_filename_ = *dir + "/" + stripped_filename;
707 if ( CreateLogfile(time_pid_string) ) {
712 // If we never succeeded, we have to give up
713 if ( success == false ) {
714 perror("Could not create logging file");
715 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", time_pid_string);
720 // Write a header message into the log file
721 char file_header_string[512]; // Enough chars for time and binary info
722 ostrstream file_header_stream(file_header_string,
723 sizeof(file_header_string));
724 file_header_stream.fill('0');
725 file_header_stream << "Log file created at: "
726 << 1900+tm_time.tm_year << '/'
727 << setw(2) << 1+tm_time.tm_mon << '/'
728 << setw(2) << tm_time.tm_mday
730 << setw(2) << tm_time.tm_hour << ':'
731 << setw(2) << tm_time.tm_min << ':'
732 << setw(2) << tm_time.tm_sec << '\n'
733 << "Running on machine: "
734 << LogDestination::hostname() << '\n'
736 int header_len = strlen(file_header_string);
737 fwrite(file_header_string, 1, header_len, file_);
738 file_length_ += header_len;
739 bytes_since_flush_ += header_len;
743 if ( !stop_writing ) {
744 // fwrite() doesn't return an error when the disk is full, for
745 // messages that are less than 4096 bytes. When the disk is full,
746 // it returns the message length for messages that are less than
747 // 4096 bytes. fwrite() returns 4096 for message lengths that are
748 // greater than 4096, thereby indicating an error.
750 fwrite(message, 1, message_len, file_);
751 if ( FLAGS_stop_logging_if_full_disk &&
752 errno == ENOSPC ) { // disk full, stop writing to disk
753 stop_writing = true; // until the disk is
756 file_length_ += message_len;
757 bytes_since_flush_ += message_len;
760 if ( CycleClock_Now() >= next_flush_time_ )
761 stop_writing = false; // check to see if disk has free space.
762 return; // no need to flush
765 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
766 // or every "FLAGS_logbufsecs" seconds.
768 (bytes_since_flush_ >= 1000000) ||
769 (CycleClock_Now() >= next_flush_time_) ) {
774 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
776 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
777 assert(severity >=0 && severity < NUM_SEVERITIES);
778 if (!log_destinations_[severity]) {
779 log_destinations_[severity] = new LogDestination(severity, NULL);
781 return log_destinations_[severity];
784 // Get the part of filepath after the last path separator.
785 // (Doesn't modify filepath, contrary to basename() in libgen.h.)
786 static const char* const_basename(const char* filepath) {
787 const char* base = strrchr(filepath, '/');
788 #ifdef OS_WINDOWS // Look for either path separator in Windows
790 base = strrchr(filepath, '\\');
792 return base ? (base+1) : filepath;
796 // LogMessage's constructor starts each message with a string like:
797 // I1018 160715 logging.cc:1153]
798 // (1st letter of severity level, GMT month, date, & time;
799 // thread id (if not 0x400); basename of file and line of the logging command)
800 // We ignore thread id 0x400 because it seems to be the default for single-
801 // threaded programs.
803 // An arbitrary limit on the length of a single log message. This
804 // is so that streaming can be done more efficiently.
805 const size_t LogMessage::kMaxLogMessageLen = 30000;
807 // Need to reserve some space for FATAL messages because
808 // we usually do LOG(FATAL) when we ran out of heap memory.
809 // However, since LogMessage() also calls new[], in this case,
810 // it will recusively call LOG(FATAL), which then call new[] ... etc.
811 // Eventually, the program will run out of stack memory and no message
812 // will get logged. Note that we will not be protecting this buffer
813 // with a lock because the chances are very small that there will
814 // be a contention during LOG(FATAL) which can only happen at most
816 static char fatal_message_buffer[LogMessage::kMaxLogMessageLen+1];
818 // Similarly we reserve space for a LogMessageData struct to be used
819 // for FATAL messages.
820 LogMessage::LogMessageData LogMessage::fatal_message_data_(0, FATAL, 0);
822 LogMessage::LogMessageData::LogMessageData(int preserved_errno,
823 LogSeverity severity,
825 // ORDER DEPENDENCY: buf_ comes before message_text_ comes before stream_
826 preserved_errno_(preserved_errno),
827 // Use static buffer for LOG(FATAL)
828 buf_((severity != FATAL) ? new char[kMaxLogMessageLen+1] : NULL),
829 message_text_((severity != FATAL) ? buf_ : fatal_message_buffer),
830 stream_(message_text_, kMaxLogMessageLen, ctr),
831 severity_(severity) {
834 LogMessage::LogMessageData::~LogMessageData() {
838 LogMessage::LogMessageData* LogMessage::GetMessageData(int preserved_errno,
839 LogSeverity severity,
841 if (severity != FATAL) {
844 fatal_message_data_.preserved_errno_ = preserved_errno;
845 fatal_message_data_.stream_.set_ctr(ctr);
846 return &fatal_message_data_;
850 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
851 int ctr, void (LogMessage::*send_method)()) :
852 allocated_((severity != FATAL) ?
853 new LogMessageData(errno, severity, ctr) : NULL),
854 data_(GetMessageData(errno, severity, ctr)) {
855 Init(file, line, severity, send_method);
858 LogMessage::LogMessage(const char* file, int line, const CheckOpString& result)
860 data_(GetMessageData(errno, FATAL, 0)) {
861 Init(file, line, FATAL, &LogMessage::SendToLog);
862 stream() << "Check failed: " << (*result.str_) << " ";
865 LogMessage::LogMessage(const char* file, int line) :
866 allocated_(new LogMessageData(errno, INFO, 0)),
867 data_(GetMessageData(errno, INFO, 0)) {
868 Init(file, line, INFO, &LogMessage::SendToLog);
871 LogMessage::LogMessage(const char* file, int line, LogSeverity severity) :
872 allocated_((severity != FATAL) ?
873 new LogMessageData(errno, severity, 0) : NULL),
874 data_(GetMessageData(errno, severity, 0)) {
875 Init(file, line, severity, &LogMessage::SendToLog);
878 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
880 allocated_((severity != FATAL) ?
881 new LogMessageData(errno, severity, 0) : NULL),
882 data_(GetMessageData(errno, severity, 0)) {
883 Init(file, line, severity, &LogMessage::SendToSinkAndLog);
884 data_->sink_ = sink; // override Init()'s setting to NULL
887 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
888 vector<string> *outvec) :
889 allocated_((severity != FATAL) ?
890 new LogMessageData(errno, severity, 0) : NULL),
891 data_(GetMessageData(errno, severity, 0)) {
892 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
893 data_->outvec_ = outvec; // override Init()'s setting to NULL
896 void LogMessage::Init(const char* file, int line, LogSeverity severity,
897 void (LogMessage::*send_method)()) {
899 data_->send_method_ = send_method;
901 data_->outvec_ = NULL;
903 data_->timestamp_ = time(NULL);
904 localtime_r(&data_->timestamp_, &data_->tm_time_);
905 RawLog__SetLastTime(data_->tm_time_);
906 data_->basename_ = const_basename(file);
907 data_->fullname_ = file;
908 data_->stream_.fill('0');
910 // In some cases, we use logging like a print mechanism and
911 // the prefixes get in the way
912 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
913 if ( is_default_thread() ) {
914 stream() << LogSeverityNames[severity][0]
915 << setw(2) << 1+data_->tm_time_.tm_mon
916 << setw(2) << data_->tm_time_.tm_mday
918 << setw(2) << data_->tm_time_.tm_hour
919 << setw(2) << data_->tm_time_.tm_min
920 << setw(2) << data_->tm_time_.tm_sec
921 << ' ' << data_->basename_ << ':' << data_->line_ << "] ";
923 stream() << LogSeverityNames[severity][0]
924 << setw(2) << 1+data_->tm_time_.tm_mon
925 << setw(2) << data_->tm_time_.tm_mday
927 << setw(2) << data_->tm_time_.tm_hour
928 << setw(2) << data_->tm_time_.tm_min
929 << setw(2) << data_->tm_time_.tm_sec
930 << ' ' << setw(8) << std::hex << pthread_self() << std::dec
931 << ' ' << data_->basename_ << ':' << data_->line_ << "] ";
935 data_->num_prefix_chars_ = data_->stream_.pcount();
936 data_->has_been_flushed_ = false;
939 LogMessage::~LogMessage() {
944 // Flush buffered message, called by the destructor, or any other function
945 // that needs to synchronize the log.
946 void LogMessage::Flush() {
947 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
950 data_->num_chars_to_log_ = data_->stream_.pcount();
951 data_->num_chars_to_syslog_ =
952 data_->num_chars_to_log_ - data_->num_prefix_chars_;
954 // Do we need to add a \n to the end of this message?
955 bool append_newline =
956 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
957 char original_final_char = '\0';
959 // If we do need to add a \n, we'll do it by violating the memory of the
960 // ostrstream buffer. This is quick, and we'll make sure to undo our
961 // modification before anything else is done with the ostrstream. It
962 // would be preferable not to do things this way, but it seems to be
963 // the best way to deal with this.
964 if (append_newline) {
965 original_final_char = data_->message_text_[data_->num_chars_to_log_];
966 data_->message_text_[data_->num_chars_to_log_++] = '\n';
969 // Prevent any subtle race conditions by wrapping a mutex lock around
970 // the actual logging action per se.
972 MutexLock l(&log_mutex);
973 (this->*(data_->send_method_))();
974 ++num_messages_[static_cast<int>(data_->severity_)];
976 LogDestination::WaitForSinks(data_);
978 if (append_newline) {
979 // Fix the ostrstream back how it was before we screwed with it.
980 // It's 99.44% certain that we don't need to worry about doing this.
981 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
984 // If errno was already set before we enter the logging call, we'll
985 // set it back to that value when we return from the logging call.
986 // It happens often that we log an error message after a syscall
987 // failure, which can potentially set the errno to some other
988 // values. We would like to preserve the original errno.
989 if (data_->preserved_errno_ != 0) {
990 errno = data_->preserved_errno_;
993 // Note that this message is now safely logged. If we're asked to flush
994 // again, as a result of destruction, say, we'll do nothing on future calls.
995 data_->has_been_flushed_ = true;
998 // Copy of FATAL log message so that we can print it out again after
999 // all the stack traces.
1000 // We cannot simply use fatal_message_buffer, because two or more FATAL log
1001 // messages may happen in a row. This is a real possibility given that
1002 // FATAL log messages are often associated with corrupted process state.
1003 // In this case, we still want to reprint the first FATAL log message, so
1004 // we need to save away the first message in a separate buffer.
1005 static time_t fatal_time;
1006 static char fatal_message[256];
1008 void ReprintFatalMessage() {
1009 if (fatal_message[0]) {
1010 const int n = strlen(fatal_message);
1011 if (!FLAGS_logtostderr) {
1012 // Also write to stderr
1013 WriteToStderr(fatal_message, n);
1015 LogDestination::LogToAllLogfiles(ERROR, fatal_time, fatal_message, n);
1019 // L >= log_mutex (callers must hold the log_mutex).
1020 void LogMessage::SendToLog() {
1021 static bool already_warned_before_initgoogle = false;
1023 log_mutex.AssertHeld();
1025 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1026 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1028 // Messages of a given severity get logged to lower severity logs, too
1030 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1031 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1032 "written to STDERR\n";
1033 WriteToStderr(w, strlen(w));
1034 already_warned_before_initgoogle = true;
1037 // global flag: never log to file if set. Also -- don't log to a
1038 // file if we haven't parsed the command line flags to get the
1040 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1041 WriteToStderr(data_->message_text_, data_->num_chars_to_log_);
1043 // this could be protected by a flag if necessary.
1044 LogDestination::LogToSinks(data_->severity_,
1045 data_->fullname_, data_->basename_,
1046 data_->line_, &data_->tm_time_,
1047 data_->message_text_ + data_->num_prefix_chars_,
1048 (data_->num_chars_to_log_ -
1049 data_->num_prefix_chars_ - 1));
1052 // log this message to all log files of severity <= severity_
1053 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1054 data_->message_text_,
1055 data_->num_chars_to_log_);
1057 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1058 data_->num_chars_to_log_);
1059 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1060 data_->num_chars_to_log_);
1061 LogDestination::LogToSinks(data_->severity_,
1062 data_->fullname_, data_->basename_,
1063 data_->line_, &data_->tm_time_,
1064 data_->message_text_ + data_->num_prefix_chars_,
1065 (data_->num_chars_to_log_
1066 - data_->num_prefix_chars_ - 1));
1067 // NOTE: -1 removes trailing \n
1070 // If we log a FATAL message, flush all the log destinations, then toss
1071 // a signal for others to catch. We leave the logs in a state that
1072 // someone else can use them (as long as they flush afterwards)
1073 if (data_->severity_ == FATAL) {
1074 // save away the fatal message so we can print it again later
1075 const int copy = min<int>(data_->num_chars_to_log_,
1076 sizeof(fatal_message)-1);
1077 memcpy(fatal_message, data_->message_text_, copy);
1078 fatal_message[copy] = '\0';
1079 fatal_time = data_->timestamp_;
1081 if (!FLAGS_logtostderr) {
1082 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1083 if ( LogDestination::log_destinations_[i] )
1084 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1088 // release the lock that our caller (directly or indirectly)
1089 // LogMessage::~LogMessage() grabbed so that signal handlers
1090 // can use the logging facility. Alternately, we could add
1091 // an entire unsafe logging interface to bypass locking
1092 // for signal handlers but this seems simpler.
1094 LogDestination::WaitForSinks(data_);
1100 static void logging_fail() {
1101 #if defined _DEBUG && defined COMPILER_MSVC
1102 // When debugging on windows, avoid the obnoxious dialog and make
1103 // it possible to continue past a LOG(FATAL) in the debugger
1110 #ifdef HAVE___ATTRIBUTE__
1111 void (*g_logging_fail_func)() __attribute__((noreturn)) = &logging_fail;
1113 void (*g_logging_fail_func)() = &logging_fail;
1116 void InstallFailureFunction(void (*fail_func)()) {
1117 g_logging_fail_func = fail_func;
1120 void LogMessage::Fail() {
1121 g_logging_fail_func();
1124 // L >= log_mutex (callers must hold the log_mutex).
1125 void LogMessage::SendToSinkAndLog() {
1126 if (data_->sink_ != NULL) {
1127 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1128 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1129 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1130 data_->line_, &data_->tm_time_,
1131 data_->message_text_ + data_->num_prefix_chars_,
1132 (data_->num_chars_to_log_ -
1133 data_->num_prefix_chars_ - 1));
1138 // L >= log_mutex (callers must hold the log_mutex).
1139 void LogMessage::SaveOrSendToLog() {
1140 if (data_->outvec_ != NULL) {
1141 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1142 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1143 // Omit prefix of message and trailing newline when recording in outvec_.
1144 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1145 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1146 data_->outvec_->push_back(string(start, len));
1152 // L >= log_mutex (callers must hold the log_mutex).
1153 void LogMessage::SendToSyslogAndLog() {
1154 // Before any calls to syslog(), make a single call to openlog()
1155 static bool openlog_already_called = false;
1156 if (!openlog_already_called) {
1157 openlog(ProgramInvocationShortName(), LOG_CONS | LOG_NDELAY | LOG_PID,
1159 openlog_already_called = true;
1162 // This array maps Google severity levels to syslog levels
1163 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1164 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1165 int(data_->num_chars_to_syslog_),
1166 data_->message_text_ + data_->num_prefix_chars_);
1170 base::Logger* base::GetLogger(LogSeverity severity) {
1171 MutexLock l(&log_mutex);
1172 return LogDestination::log_destination(severity)->logger_;
1175 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1176 MutexLock l(&log_mutex);
1177 LogDestination::log_destination(severity)->logger_ = logger;
1180 // L < log_mutex. Acquires and releases mutex_.
1181 int64 LogMessage::num_messages(int severity) {
1182 MutexLock l(&log_mutex);
1183 return num_messages_[severity];
1186 // Output the COUNTER value. This is only valid if ostream is a
1188 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1189 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1190 CHECK(log == log->self());
1195 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1196 LogSeverity severity, int ctr,
1197 void (LogMessage::*send_method)())
1198 : LogMessage(file, line, severity, ctr, send_method) {
1201 ErrnoLogMessage::~ErrnoLogMessage() {
1202 // Don't access errno directly because it may have been altered
1203 // while streaming the message.
1205 posix_strerror_r(preserved_errno(), buf, sizeof(buf));
1206 stream() << ": " << buf << " [" << preserved_errno() << "]";
1209 void FlushLogFiles(LogSeverity min_severity) {
1210 LogDestination::FlushLogFiles(min_severity);
1213 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1214 LogDestination::FlushLogFilesUnsafe(min_severity);
1217 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1218 LogDestination::SetLogDestination(severity, base_filename);
1221 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1222 LogDestination::SetLogSymlink(severity, symlink_basename);
1225 LogSink::~LogSink() {
1228 void LogSink::WaitTillSent() {
1232 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1233 const struct ::tm* tm_time,
1234 const char* message, size_t message_len) {
1235 ostringstream stream(string(message, message_len));
1238 if ( is_default_thread() ) {
1239 stream << LogSeverityNames[severity][0]
1240 << setw(2) << 1+tm_time->tm_mon
1241 << setw(2) << tm_time->tm_mday
1243 << setw(2) << tm_time->tm_hour
1244 << setw(2) << tm_time->tm_min
1245 << setw(2) << tm_time->tm_sec
1246 << ' ' << file << ':' << line << "] ";
1248 stream << LogSeverityNames[severity][0]
1249 << setw(2) << 1+tm_time->tm_mon
1250 << setw(2) << tm_time->tm_mday
1252 << setw(2) << tm_time->tm_hour
1253 << setw(2) << tm_time->tm_min
1254 << setw(2) << tm_time->tm_sec
1255 << ' ' << setw(8) << std::hex << pthread_self() << std::dec
1256 << ' ' << file << ':' << line << "] ";
1259 stream << string(message, message_len);
1260 return stream.str();
1263 void AddLogSink(LogSink *destination) {
1264 LogDestination::AddLogSink(destination);
1267 void RemoveLogSink(LogSink *destination) {
1268 LogDestination::RemoveLogSink(destination);
1271 void SetLogFilenameExtension(const char* ext) {
1272 LogDestination::SetLogFilenameExtension(ext);
1275 void SetStderrLogging(LogSeverity min_severity) {
1276 LogDestination::SetStderrLogging(min_severity);
1279 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1280 LogDestination::SetEmailLogging(min_severity, addresses);
1283 void LogToStderr() {
1284 LogDestination::LogToStderr();
1287 // use_logging controls whether the logging functions LOG/VLOG are used
1288 // to log errors. It should be set to false when the caller holds the
1290 static bool SendEmailInternal(const char*dest, const char *subject,
1291 const char*body, bool use_logging) {
1292 if (dest && *dest) {
1293 if ( use_logging ) {
1294 VLOG(1) << "Trying to send TITLE:" << subject
1295 << " BODY:" << body << " to " << dest;
1297 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1298 subject, body, dest);
1301 string cmd(FLAGS_logmailer);
1302 cmd = cmd + " -s\"" + string(subject) + "\" " + string(dest);
1303 FILE* pipe = popen(cmd.c_str(), "w");
1305 // Add the body if we have one
1307 fwrite(body, sizeof(char), strlen(body), pipe);
1308 bool ok = pclose(pipe) != -1;
1310 if ( use_logging ) {
1312 posix_strerror_r(errno, buf, sizeof(buf));
1313 LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf;
1316 posix_strerror_r(errno, buf, sizeof(buf));
1317 fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf);
1322 if ( use_logging ) {
1323 LOG(ERROR) << "Unable to send mail to " << dest;
1325 fprintf(stderr, "Unable to send mail to %s\n", dest);
1332 bool SendEmail(const char*dest, const char *subject, const char*body){
1333 return SendEmailInternal(dest, subject, body, true);
1336 void GetTempDirectories(vector<string>* list) {
1339 // On windows we'll try to find a directory in this order:
1340 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1343 // C:/WINDOWS/ or C:/WINNT/
1346 if (GetTempPathA(MAX_PATH, tmp))
1347 list->push_back(tmp);
1348 list->push_back("C:\\tmp\\");
1349 list->push_back("C:\\temp\\");
1351 // Directories, in order of preference. If we find a dir that
1352 // exists, we stop adding other less-preferred dirs
1353 const char * candidates[] = {
1354 // Non-null only during unittest/regtest
1355 getenv("TEST_TMPDIR"),
1357 // Explicitly-supplied temp dirs
1358 getenv("TMPDIR"), getenv("TMP"),
1360 // If all else fails
1364 for (int i = 0; i < sizeof(candidates) / sizeof(*candidates); i++) {
1365 const char *d = candidates[i];
1366 if (!d) continue; // Empty env var
1368 // Make sure we don't surprise anyone who's expecting a '/'
1370 if (dstr[dstr.size() - 1] != '/') {
1373 list->push_back(dstr);
1375 struct stat statbuf;
1376 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1377 // We found a dir that exists - we're done.
1385 static vector<string>* logging_directories_list;
1387 const vector<string>& GetLoggingDirectories() {
1388 // Not strictly thread-safe but we're called early in InitGoogle().
1389 if (logging_directories_list == NULL) {
1390 logging_directories_list = new vector<string>;
1392 if ( !FLAGS_log_dir.empty() ) {
1393 // A dir was specified, we should use it
1394 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1396 GetTempDirectories(logging_directories_list);
1399 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1400 logging_directories_list->push_back(tmp);
1401 logging_directories_list->push_back(".\\");
1403 logging_directories_list->push_back("./");
1407 return *logging_directories_list;
1410 void TestOnly_ClearLoggingDirectoriesList() {
1411 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1412 "called from test code.\n");
1413 delete logging_directories_list;
1414 logging_directories_list = NULL;
1417 void GetExistingTempDirectories(vector<string>* list) {
1418 GetTempDirectories(list);
1419 vector<string>::iterator i_dir = list->begin();
1420 while( i_dir != list->end() ) {
1421 // zero arg to access means test for existence; no constant
1422 // defined on windows
1423 if ( access(i_dir->c_str(), 0) ) {
1424 i_dir = list->erase(i_dir);
1431 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1433 struct stat statbuf;
1434 const int kCopyBlockSize = 8 << 10;
1435 char copybuf[kCopyBlockSize];
1436 int64 read_offset, write_offset;
1437 // Don't follow symlinks unless they're our own fd symlinks in /proc
1439 const char *procfd_prefix = "/proc/self/fd/";
1440 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1442 int fd = open(path, flags);
1444 if (errno == EFBIG) {
1445 // The log file in question has got too big for us to open. The
1446 // real fix for this would be to compile logging.cc (or probably
1447 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1449 // Instead just truncate the file to something we can manage
1450 if (truncate(path, 0) == -1) {
1451 PLOG(ERROR) << "Unable to truncate " << path;
1453 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1456 PLOG(ERROR) << "Unable to open " << path;
1461 if (fstat(fd, &statbuf) == -1) {
1462 PLOG(ERROR) << "Unable to fstat()";
1466 // See if the path refers to a regular file bigger than the
1468 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1469 if (statbuf.st_size <= limit) goto out_close_fd;
1470 if (statbuf.st_size <= keep) goto out_close_fd;
1472 // This log file is too large - we need to truncate it
1473 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1475 // Copy the last "keep" bytes of the file to the beginning of the file
1476 read_offset = statbuf.st_size - keep;
1478 int bytesin, bytesout;
1479 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1480 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1481 if (bytesout == -1) {
1482 PLOG(ERROR) << "Unable to write to " << path;
1484 } else if (bytesout != bytesin) {
1485 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1487 read_offset += bytesin;
1488 write_offset += bytesout;
1490 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1492 // Truncate the remainder of the file. If someone else writes to the
1493 // end of the file after our last read() above, we lose their latest
1494 // data. Too bad ...
1495 if (ftruncate(fd, write_offset) == -1) {
1496 PLOG(ERROR) << "Unable to truncate " << path;
1504 void TruncateStdoutStderr() {
1505 int64 limit = FLAGS_max_log_size << 20;
1506 int64 keep = 1 << 20;
1507 TruncateLogFile("/proc/self/fd/1", limit, keep);
1508 TruncateLogFile("/proc/self/fd/2", limit, keep);
1512 // Helper functions for string comparisons.
1513 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1514 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1515 const char* names) { \
1516 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1517 if (equal == expected) return NULL; \
1520 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1521 return new string(ss.str(), ss.pcount()); \
1524 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1525 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1526 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1527 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1528 #undef DEFINE_CHECK_STROP_IMPL
1530 int posix_strerror_r(int err, char *buf, size_t len) {
1531 // Sanity check input parameters
1532 if (buf == NULL || len <= 0) {
1537 // Reset buf and errno, and try calling whatever version of strerror_r()
1538 // is implemented by glibc
1540 int old_errno = errno;
1542 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1544 // Both versions set errno on failure
1546 // Should already be there, but better safe than sorry
1552 // POSIX is vague about whether the string will be terminated, although
1553 // is indirectly implies that typically ERANGE will be returned, instead
1554 // of truncating the string. This is different from the GNU implementation.
1555 // We play it safe by always terminating the string explicitly.
1556 buf[len-1] = '\000';
1558 // If the function succeeded, we can use its exit code to determine the
1559 // semantics implemented by glibc
1563 // GNU semantics detected
1568 #if defined(OS_MACOSX) || defined(OS_FREEBSD)
1569 if (reinterpret_cast<int>(rc) < sys_nerr) {
1570 // This means an error on MacOSX or FreeBSD.
1574 strncat(buf, rc, len-1);
1580 LogMessageFatal::LogMessageFatal(const char* file, int line) :
1581 LogMessage(file, line, FATAL) {}
1583 LogMessageFatal::LogMessageFatal(const char* file, int line,
1584 const CheckOpString& result) :
1585 LogMessage(file, line, result) {}
1587 LogMessageFatal::~LogMessageFatal() {
1592 _END_GOOGLE_NAMESPACE_