1 #define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite()
9 # include <unistd.h> // For _exit.
12 #include <sys/types.h>
14 #ifdef HAVE_SYS_UTSNAME_H
15 # include <sys/utsname.h> // For uname.
29 #include <errno.h> // for errno
31 #include "base/commandlineflags.h" // to get the program name
32 #include "glog/logging.h"
33 #include "glog/raw_logging.h"
34 #include "base/googleinit.h"
38 using std::ostrstream;
44 using std::ostringstream;
47 DEFINE_bool(logtostderr, false,
48 "log messages go to stderr instead of logfiles");
49 DEFINE_bool(alsologtostderr, false,
50 "log messages go to stderr in addition to logfiles");
52 // By default, errors (including fatal errors) get logged to stderr as
55 // The default is ERROR instead of FATAL so that users can see problems
56 // when they run a program without having to look in another file.
57 DEFINE_int32(stderrthreshold,
58 GOOGLE_NAMESPACE::ERROR,
59 "log messages at or above this level are copied to stderr in "
60 "addition to logfiles. This flag obsoletes --alsologtostderr.");
62 DEFINE_string(alsologtoemail, "",
63 "log messages go to these email addresses "
64 "in addition to logfiles");
65 DEFINE_bool(log_prefix, true,
66 "Prepend the log prefix to the start of each log line");
67 DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
68 "actually get logged anywhere");
69 DEFINE_int32(logbuflevel, 0,
70 "Buffer log messages logged at this level or lower"
71 " (-1 means don't buffer; 0 means buffer INFO only;"
73 DEFINE_int32(logbufsecs, 30,
74 "Buffer log messages for at most this many seconds");
75 DEFINE_int32(logemaillevel, 999,
76 "Email log messages logged at this level or higher"
77 " (0 means email all; 3 means email FATAL only;"
79 DEFINE_string(logmailer, "/bin/mail",
80 "Mailer used to send logging email");
82 // Compute the default value for --log_dir
83 static const char* DefaultLogDir() {
85 env = getenv("GOOGLE_LOG_DIR");
86 if (env != NULL && env[0] != '\0') {
89 env = getenv("TEST_TMPDIR");
90 if (env != NULL && env[0] != '\0') {
96 DEFINE_string(log_dir, DefaultLogDir(),
97 "If specified, logfiles are written into this directory instead "
98 "of the default logging directory.");
99 DEFINE_string(log_link, "", "Put additional links to the log "
100 "files in this directory");
102 DEFINE_int32(max_log_size, 1800,
103 "approx. maximum log file size (in MB)");
105 DEFINE_bool(stop_logging_if_full_disk, false,
106 "Stop attempting to log to disk if the disk is full.");
108 // TODO(hamaji): consider windows
109 #define PATH_SEPARATOR '/'
111 static void GetHostName(string* hostname) {
112 #if defined(HAVE_SYS_UTSNAME_H)
114 if (0 != uname(&buf)) {
115 // ensure null termination on failure
116 *buf.nodename = '\0';
118 *hostname = buf.nodename;
119 #elif defined(OS_WINDOWS)
122 if (GetComputerNameA(buf, &len)) {
128 # warning There is no way to retrieve the host name.
129 *hostname = "(unknown)";
133 _START_GOOGLE_NAMESPACE_
135 // A mutex that allows only one thread to log at a time, to keep things from
136 // getting jumbled. Some other very uncommon logging operations (like
137 // changing the destination file for log messages of a given severity) also
138 // lock this mutex. Please be sure that anybody who might possibly need to
140 static Mutex log_mutex;
142 // Number of messages sent at each severity. Under log_mutex.
143 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
145 // Globally disable log writing (if disk is full)
146 static bool stop_writing = false;
148 const char*const LogSeverityNames[NUM_SEVERITIES] = {
149 "INFO", "WARNING", "ERROR", "FATAL"
152 const char* GetLogSeverityName(LogSeverity severity) {
153 return LogSeverityNames[severity];
156 static bool SendEmailInternal(const char*dest, const char *subject,
157 const char*body, bool use_logging);
159 base::Logger::~Logger() {
164 // Encapsulates all file-system related state
165 class LogFileObject : public base::Logger {
167 LogFileObject(LogSeverity severity, const char* base_filename);
170 virtual void Write(bool force_flush, // Should we force a flush here?
171 time_t timestamp, // Timestamp for this entry
175 // Configuration options
176 void SetBasename(const char* basename);
177 void SetExtension(const char* ext);
178 void SetSymlinkBasename(const char* symlink_basename);
180 // Normal flushing routine
181 virtual void Flush();
183 // It is the actual file length for the system loggers,
184 // i.e., INFO, ERROR, etc.
185 virtual uint32 LogSize() {
190 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
191 // can avoid grabbing a lock. Usually Flush() calls it after
193 void FlushUnlocked();
196 static const uint32 kRolloverAttemptFrequency = 0x20;
199 bool base_filename_selected_;
200 string base_filename_;
201 string symlink_basename_;
202 string filename_extension_; // option users can specify (eg to add port#)
204 LogSeverity severity_;
205 uint32 bytes_since_flush_;
207 unsigned int rollover_attempt_;
208 int64 next_flush_time_; // cycle count at which to flush log
210 // Actually create a logfile using the value of base_filename_ and the
211 // supplied argument time_pid_string
212 // REQUIRES: lock_ is held
213 bool CreateLogfile(const char* time_pid_string);
218 class LogDestination {
220 friend class LogMessage;
221 friend void ReprintFatalMessage();
222 friend base::Logger* base::GetLogger(LogSeverity);
223 friend void base::SetLogger(LogSeverity, base::Logger*);
225 // These methods are just forwarded to by their global versions.
226 static void SetLogDestination(LogSeverity severity,
227 const char* base_filename);
228 static void SetLogSymlink(LogSeverity severity,
229 const char* symlink_basename);
230 static void AddLogSink(LogSink *destination);
231 static void RemoveLogSink(LogSink *destination);
232 static void SetLogFilenameExtension(const char* filename_extension);
233 static void SetStderrLogging(LogSeverity min_severity);
234 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
235 static void LogToStderr();
236 // Flush all log files that are at least at the given severity level
237 static void FlushLogFiles(int min_severity);
238 static void FlushLogFilesUnsafe(int min_severity);
240 // we set the maximum size of our packet to be 1400, the logic being
241 // to prevent fragmentation.
242 // Really this number is arbitrary.
243 static const int kNetworkBytes = 1400;
245 static const string& hostname();
248 LogDestination(LogSeverity severity, const char* base_filename);
249 ~LogDestination() { }
251 // Take a log message of a particular severity and log it to stderr
252 // iff it's of a high enough severity to deserve it.
253 static void MaybeLogToStderr(LogSeverity severity, const char* message,
256 // Take a log message of a particular severity and log it to email
257 // iff it's of a high enough severity to deserve it.
258 static void MaybeLogToEmail(LogSeverity severity, const char* message,
260 // Take a log message of a particular severity and log it to a file
261 // iff the base filename is not "" (which means "don't log to me")
262 static void MaybeLogToLogfile(LogSeverity severity,
264 const char* message, size_t len);
265 // Take a log message of a particular severity and log it to the file
266 // for that severity and also for all files with severity less than
268 static void LogToAllLogfiles(LogSeverity severity,
270 const char* message, size_t len);
272 // Send logging info to all registered sinks.
273 static void LogToSinks(LogSeverity severity,
274 const char *full_filename,
275 const char *base_filename,
277 const struct ::tm* tm_time,
281 // Wait for all registered sinks via WaitTillSent
282 // including the optional one in "data".
283 static void WaitForSinks(LogMessage::LogMessageData* data);
285 static LogDestination* log_destination(LogSeverity severity);
287 LogFileObject fileobject_;
288 base::Logger* logger_; // Either &fileobject_, or wrapper around it
290 static LogDestination* log_destinations_[NUM_SEVERITIES];
291 static LogSeverity email_logging_severity_;
292 static string addresses_;
293 static string hostname_;
295 // arbitrary global logging destinations.
296 static vector<LogSink*>* sinks_;
298 // Protects the vector sinks_,
299 // but not the LogSink objects its elements reference.
300 static Mutex sink_mutex_;
303 LogDestination(const LogDestination&);
304 LogDestination& operator=(const LogDestination&);
307 // Errors do not get logged to email by default.
308 LogSeverity LogDestination::email_logging_severity_ = 99999;
310 string LogDestination::addresses_ = "";
311 string LogDestination::hostname_ = "";
313 vector<LogSink*>* LogDestination::sinks_ = NULL;
314 Mutex LogDestination::sink_mutex_;
317 const string& LogDestination::hostname() {
318 if (hostname_.empty()) {
319 GetHostName(&hostname_);
320 if (hostname_.empty()) {
321 hostname_ = "(unknown)";
327 LogDestination::LogDestination(LogSeverity severity,
328 const char* base_filename)
329 : fileobject_(severity, base_filename),
330 logger_(&fileobject_) {
333 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
334 // assume we have the log_mutex or we simply don't care
336 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
337 LogDestination* log = log_destination(i);
339 // Flush the base fileobject_ logger directly instead of going
340 // through any wrappers to reduce chance of deadlock.
341 log->fileobject_.FlushUnlocked();
346 inline void LogDestination::FlushLogFiles(int min_severity) {
347 // Prevent any subtle race conditions by wrapping a mutex lock around
349 MutexLock l(&log_mutex);
350 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
351 LogDestination* log = log_destination(i);
353 log->logger_->Flush();
358 inline void LogDestination::SetLogDestination(LogSeverity severity,
359 const char* base_filename) {
360 assert(severity >= 0 && severity < NUM_SEVERITIES);
361 // Prevent any subtle race conditions by wrapping a mutex lock around
363 MutexLock l(&log_mutex);
364 log_destination(severity)->fileobject_.SetBasename(base_filename);
367 inline void LogDestination::SetLogSymlink(LogSeverity severity,
368 const char* symlink_basename) {
369 CHECK_GE(severity, 0);
370 CHECK_LT(severity, NUM_SEVERITIES);
371 MutexLock l(&log_mutex);
372 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
375 inline void LogDestination::AddLogSink(LogSink *destination) {
376 // Prevent any subtle race conditions by wrapping a mutex lock around
378 MutexLock l(&sink_mutex_);
379 if (!sinks_) sinks_ = new vector<LogSink*>;
380 sinks_->push_back(destination);
383 inline void LogDestination::RemoveLogSink(LogSink *destination) {
384 // Prevent any subtle race conditions by wrapping a mutex lock around
386 MutexLock l(&sink_mutex_);
387 // This doesn't keep the sinks in order, but who cares?
389 for (int i = sinks_->size() - 1; i >= 0; i--) {
390 if ((*sinks_)[i] == destination) {
391 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
399 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
400 // Prevent any subtle race conditions by wrapping a mutex lock around
402 MutexLock l(&log_mutex);
403 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
404 log_destination(severity)->fileobject_.SetExtension(ext);
408 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
409 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
410 // Prevent any subtle race conditions by wrapping a mutex lock around
412 MutexLock l(&log_mutex);
413 FLAGS_stderrthreshold = min_severity;
416 inline void LogDestination::LogToStderr() {
417 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
418 // SetLogDestination already do the locking!
419 SetStderrLogging(0); // thus everything is "also" logged to stderr
420 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
421 SetLogDestination(i, ""); // "" turns off logging to a logfile
425 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
426 const char* addresses) {
427 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
428 // Prevent any subtle race conditions by wrapping a mutex lock around
430 MutexLock l(&log_mutex);
431 LogDestination::email_logging_severity_ = min_severity;
432 LogDestination::addresses_ = addresses;
435 static void WriteToStderr(const char* message, size_t len) {
436 // Avoid using cerr from this module since we may get called during
437 // exit code, and cerr may be partially or fully destroyed by then.
438 write(STDERR_FILENO, message, len);
441 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
442 const char* message, size_t len) {
443 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
444 WriteToStderr(message, len);
446 // On Windows, also output to the debugger
447 ::OutputDebugStringA(string(message,len).c_str());
453 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
454 const char* message, size_t len) {
455 if (severity >= email_logging_severity_ ||
456 severity >= FLAGS_logemaillevel) {
457 string to(FLAGS_alsologtoemail);
458 if (!addresses_.empty()) {
464 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
465 ProgramInvocationShortName());
466 string body(hostname());
468 body.append(message, len);
470 // should NOT use SendEmail(). The caller of this function holds the
471 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
472 // acquire the log_mutex object. Use SendEmailInternal() and set
473 // use_logging to false.
474 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
479 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
483 const bool should_flush = severity > FLAGS_logbuflevel;
484 LogDestination* destination = log_destination(severity);
485 destination->logger_->Write(should_flush, timestamp, message, len);
488 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
493 if ( FLAGS_logtostderr ) // global flag: never log to file
494 WriteToStderr(message, len);
496 for (int i = severity; i >= 0; --i)
497 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
501 inline void LogDestination::LogToSinks(LogSeverity severity,
502 const char *full_filename,
503 const char *base_filename,
505 const struct ::tm* tm_time,
507 size_t message_len) {
508 ReaderMutexLock l(&sink_mutex_);
510 for (int i = sinks_->size() - 1; i >= 0; i--) {
511 (*sinks_)[i]->send(severity, full_filename, base_filename,
512 line, tm_time, message, message_len);
517 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
518 ReaderMutexLock l(&sink_mutex_);
520 for (int i = sinks_->size() - 1; i >= 0; i--) {
521 (*sinks_)[i]->WaitTillSent();
524 if (data->send_method_ == &LogMessage::SendToSinkAndLog &&
525 data->sink_ != NULL) {
526 data->sink_->WaitTillSent();
530 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
532 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
533 assert(severity >=0 && severity < NUM_SEVERITIES);
534 if (!log_destinations_[severity]) {
535 log_destinations_[severity] = new LogDestination(severity, NULL);
537 return log_destinations_[severity];
542 LogFileObject::LogFileObject(LogSeverity severity,
543 const char* base_filename)
544 : base_filename_selected_(base_filename != NULL),
545 base_filename_((base_filename != NULL) ? base_filename : ""),
546 symlink_basename_(ProgramInvocationShortName()),
547 filename_extension_(),
550 bytes_since_flush_(0),
552 rollover_attempt_(kRolloverAttemptFrequency-1),
553 next_flush_time_(0) {
554 assert(severity >= 0);
555 assert(severity < NUM_SEVERITIES);
558 LogFileObject::~LogFileObject() {
566 void LogFileObject::SetBasename(const char* basename) {
568 base_filename_selected_ = true;
569 if (base_filename_ != basename) {
570 // Get rid of old log file since we are changing names
574 rollover_attempt_ = kRolloverAttemptFrequency-1;
576 base_filename_ = basename;
580 void LogFileObject::SetExtension(const char* ext) {
582 if (filename_extension_ != ext) {
583 // Get rid of old log file since we are changing names
587 rollover_attempt_ = kRolloverAttemptFrequency-1;
589 filename_extension_ = ext;
593 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
595 symlink_basename_ = symlink_basename;
598 void LogFileObject::Flush() {
603 void LogFileObject::FlushUnlocked(){
606 bytes_since_flush_ = 0;
608 // Figure out when we are due for another flush.
609 const int64 next = (FLAGS_logbufsecs
610 * static_cast<int64>(1000000)); // in usec
611 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
614 bool LogFileObject::CreateLogfile(const char* time_pid_string) {
615 string string_filename = base_filename_+filename_extension_+
617 const char* filename = string_filename.c_str();
618 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
619 if (fd == -1) return false;
621 // Mark the file close-on-exec. We don't really care if this fails
622 fcntl(fd, F_SETFD, FD_CLOEXEC);
625 file_ = fdopen(fd, "a"); // Make a FILE*.
626 if (file_ == NULL) { // Man, we're screwed!
628 unlink(filename); // Erase the half-baked evidence: an unusable log file
632 // We try to create a symlink called <program_name>.<severity>,
633 // which is easier to use. (Every time we create a new logfile,
634 // we destroy the old symlink and create a new one, so it always
635 // points to the latest logfile.) If it fails, we're sad but it's
637 if (!symlink_basename_.empty()) {
638 // take directory from filename
639 const char* slash = strrchr(filename, PATH_SEPARATOR);
640 const string linkname =
641 symlink_basename_ + '.' + LogSeverityNames[severity_];
643 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
644 linkpath += linkname;
645 unlink(linkpath.c_str()); // delete old one if it exists
647 // We must have unistd.h.
649 // Make the symlink be relative (in the same dir) so that if the
650 // entire log directory gets relocated the link is still valid.
651 const char *linkdest = slash ? (slash + 1) : filename;
652 symlink(linkdest, linkpath.c_str()); // silently ignore failures
654 // Make an additional link to the log file in a place specified by
655 // FLAGS_log_link, if indicated
656 if (!FLAGS_log_link.empty()) {
657 linkpath = FLAGS_log_link + "/" + linkname;
658 unlink(linkpath.c_str()); // delete old one if it exists
659 symlink(filename, linkpath.c_str()); // silently ignore failures
664 return true; // Everything worked
667 void LogFileObject::Write(bool force_flush,
673 // We don't log if the base_name_ is "" (which means "don't write")
674 if (base_filename_selected_ && base_filename_.empty()) {
678 if (static_cast<int>(file_length_ >> 20) >= FLAGS_max_log_size) {
681 file_length_ = bytes_since_flush_ = 0;
682 rollover_attempt_ = kRolloverAttemptFrequency-1;
685 // If there's no destination file, make one before outputting
687 // Try to rollover the log file every 32 log messages. The only time
688 // this could matter would be when we have trouble creating the log
689 // file. If that happens, we'll lose lots of log messages, of course!
690 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
691 rollover_attempt_ = 0;
694 localtime_r(×tamp, &tm_time);
696 // The logfile's filename will have the date/time & pid in it
697 char time_pid_string[256]; // More than enough chars for time, pid, \0
698 ostrstream time_pid_stream(time_pid_string, sizeof(time_pid_string));
699 time_pid_stream.fill('0');
700 time_pid_stream << 1900+tm_time.tm_year
701 << setw(2) << 1+tm_time.tm_mon
702 << setw(2) << tm_time.tm_mday
704 << setw(2) << tm_time.tm_hour
705 << setw(2) << tm_time.tm_min
706 << setw(2) << tm_time.tm_sec
708 << GetMainThreadPid()
711 if (base_filename_selected_) {
712 if (!CreateLogfile(time_pid_string)) {
713 perror("Could not create log file");
714 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", time_pid_string);
718 // If no base filename for logs of this severity has been set, use a
719 // default base filename of
720 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
721 // logfiles will have names like
722 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
723 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
724 // and 4354 is the pid of the logging process. The date & time reflect
725 // when the file was created for output.
727 // Where does the file get put? Successively try the directories
729 string stripped_filename(ProgramInvocationShortName()); // in cmdlineflag
731 GetHostName(&hostname);
733 string uidname = MyUserName();
734 // We should not call CHECK() here because this function can be
735 // called after holding on to log_mutex. We don't want to
736 // attempt to hold on to the same mutex, and get into a
737 // deadlock. Simply use a name like invalid-user.
738 if (uidname.empty()) uidname = "invalid-user";
740 stripped_filename = stripped_filename+'.'+hostname+'.'
742 +LogSeverityNames[severity_]+'.';
743 // We're going to (potentially) try to put logs in several different dirs
744 const vector<string> & log_dirs = GetLoggingDirectories();
746 // Go through the list of dirs, and try to create the log file in each
747 // until we succeed or run out of options
748 bool success = false;
749 for (vector<string>::const_iterator dir = log_dirs.begin();
750 dir != log_dirs.end();
752 base_filename_ = *dir + "/" + stripped_filename;
753 if ( CreateLogfile(time_pid_string) ) {
758 // If we never succeeded, we have to give up
759 if ( success == false ) {
760 perror("Could not create logging file");
761 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", time_pid_string);
766 // Write a header message into the log file
767 char file_header_string[512]; // Enough chars for time and binary info
768 ostrstream file_header_stream(file_header_string,
769 sizeof(file_header_string));
770 file_header_stream.fill('0');
771 file_header_stream << "Log file created at: "
772 << 1900+tm_time.tm_year << '/'
773 << setw(2) << 1+tm_time.tm_mon << '/'
774 << setw(2) << tm_time.tm_mday
776 << setw(2) << tm_time.tm_hour << ':'
777 << setw(2) << tm_time.tm_min << ':'
778 << setw(2) << tm_time.tm_sec << '\n'
779 << "Running on machine: "
780 << LogDestination::hostname() << '\n'
782 int header_len = strlen(file_header_string);
783 fwrite(file_header_string, 1, header_len, file_);
784 file_length_ += header_len;
785 bytes_since_flush_ += header_len;
789 if ( !stop_writing ) {
790 // fwrite() doesn't return an error when the disk is full, for
791 // messages that are less than 4096 bytes. When the disk is full,
792 // it returns the message length for messages that are less than
793 // 4096 bytes. fwrite() returns 4096 for message lengths that are
794 // greater than 4096, thereby indicating an error.
796 fwrite(message, 1, message_len, file_);
797 if ( FLAGS_stop_logging_if_full_disk &&
798 errno == ENOSPC ) { // disk full, stop writing to disk
799 stop_writing = true; // until the disk is
802 file_length_ += message_len;
803 bytes_since_flush_ += message_len;
806 if ( CycleClock_Now() >= next_flush_time_ )
807 stop_writing = false; // check to see if disk has free space.
808 return; // no need to flush
811 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
812 // or every "FLAGS_logbufsecs" seconds.
814 (bytes_since_flush_ >= 1000000) ||
815 (CycleClock_Now() >= next_flush_time_) ) {
823 // LogMessage's constructor starts each message with a string like:
824 // I1018 160715 logging.cc:1153]
825 // (1st letter of severity level, GMT month, date, & time;
826 // thread id (if not 0x400); basename of file and line of the logging command)
827 // We ignore thread id 0x400 because it seems to be the default for single-
828 // threaded programs.
830 // An arbitrary limit on the length of a single log message. This
831 // is so that streaming can be done more efficiently.
832 const size_t LogMessage::kMaxLogMessageLen = 30000;
834 // Need to reserve some space for FATAL messages because
835 // we usually do LOG(FATAL) when we ran out of heap memory.
836 // However, since LogMessage() also calls new[], in this case,
837 // it will recusively call LOG(FATAL), which then call new[] ... etc.
838 // Eventually, the program will run out of stack memory and no message
839 // will get logged. Note that we will not be protecting this buffer
840 // with a lock because the chances are very small that there will
841 // be a contention during LOG(FATAL) which can only happen at most
843 static char fatal_message_buffer[LogMessage::kMaxLogMessageLen+1];
845 // Similarly we reserve space for a LogMessageData struct to be used
846 // for FATAL messages.
847 LogMessage::LogMessageData LogMessage::fatal_message_data_(0, FATAL, 0);
849 LogMessage::LogMessageData::LogMessageData(int preserved_errno,
850 LogSeverity severity,
852 // ORDER DEPENDENCY: buf_ comes before message_text_ comes before stream_
853 preserved_errno_(preserved_errno),
854 // Use static buffer for LOG(FATAL)
855 buf_((severity != FATAL) ? new char[kMaxLogMessageLen+1] : NULL),
856 message_text_((severity != FATAL) ? buf_ : fatal_message_buffer),
857 stream_(message_text_, kMaxLogMessageLen, ctr),
858 severity_(severity) {
861 LogMessage::LogMessageData::~LogMessageData() {
865 LogMessage::LogMessageData* LogMessage::GetMessageData(int preserved_errno,
866 LogSeverity severity,
868 if (severity != FATAL) {
871 fatal_message_data_.preserved_errno_ = preserved_errno;
872 fatal_message_data_.stream_.set_ctr(ctr);
873 return &fatal_message_data_;
877 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
878 int ctr, void (LogMessage::*send_method)()) :
879 allocated_((severity != FATAL) ?
880 new LogMessageData(errno, severity, ctr) : NULL),
881 data_(GetMessageData(errno, severity, ctr)) {
882 Init(file, line, severity, send_method);
885 LogMessage::LogMessage(const char* file, int line, const CheckOpString& result)
887 data_(GetMessageData(errno, FATAL, 0)) {
888 Init(file, line, FATAL, &LogMessage::SendToLog);
889 stream() << "Check failed: " << (*result.str_) << " ";
892 LogMessage::LogMessage(const char* file, int line) :
893 allocated_(new LogMessageData(errno, INFO, 0)),
894 data_(GetMessageData(errno, INFO, 0)) {
895 Init(file, line, INFO, &LogMessage::SendToLog);
898 LogMessage::LogMessage(const char* file, int line, LogSeverity severity) :
899 allocated_((severity != FATAL) ?
900 new LogMessageData(errno, severity, 0) : NULL),
901 data_(GetMessageData(errno, severity, 0)) {
902 Init(file, line, severity, &LogMessage::SendToLog);
905 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
907 allocated_((severity != FATAL) ?
908 new LogMessageData(errno, severity, 0) : NULL),
909 data_(GetMessageData(errno, severity, 0)) {
910 Init(file, line, severity, &LogMessage::SendToSinkAndLog);
911 data_->sink_ = sink; // override Init()'s setting to NULL
914 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
915 vector<string> *outvec) :
916 allocated_((severity != FATAL) ?
917 new LogMessageData(errno, severity, 0) : NULL),
918 data_(GetMessageData(errno, severity, 0)) {
919 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
920 data_->outvec_ = outvec; // override Init()'s setting to NULL
923 void LogMessage::Init(const char* file, int line, LogSeverity severity,
924 void (LogMessage::*send_method)()) {
926 data_->send_method_ = send_method;
928 data_->outvec_ = NULL;
930 data_->timestamp_ = time(NULL);
931 localtime_r(&data_->timestamp_, &data_->tm_time_);
932 RawLog__SetLastTime(data_->tm_time_);
933 data_->basename_ = const_basename(file);
934 data_->fullname_ = file;
935 data_->stream_.fill('0');
937 // In some cases, we use logging like a print mechanism and
938 // the prefixes get in the way
939 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
940 if ( is_default_thread() ) {
941 stream() << LogSeverityNames[severity][0]
942 << setw(2) << 1+data_->tm_time_.tm_mon
943 << setw(2) << data_->tm_time_.tm_mday
945 << setw(2) << data_->tm_time_.tm_hour
946 << setw(2) << data_->tm_time_.tm_min
947 << setw(2) << data_->tm_time_.tm_sec
948 << ' ' << data_->basename_ << ':' << data_->line_ << "] ";
950 stream() << LogSeverityNames[severity][0]
951 << setw(2) << 1+data_->tm_time_.tm_mon
952 << setw(2) << data_->tm_time_.tm_mday
954 << setw(2) << data_->tm_time_.tm_hour
955 << setw(2) << data_->tm_time_.tm_min
956 << setw(2) << data_->tm_time_.tm_sec
957 << ' ' << setw(8) << std::hex << pthread_self() << std::dec
958 << ' ' << data_->basename_ << ':' << data_->line_ << "] ";
962 data_->num_prefix_chars_ = data_->stream_.pcount();
963 data_->has_been_flushed_ = false;
966 LogMessage::~LogMessage() {
971 // Flush buffered message, called by the destructor, or any other function
972 // that needs to synchronize the log.
973 void LogMessage::Flush() {
974 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
977 data_->num_chars_to_log_ = data_->stream_.pcount();
978 data_->num_chars_to_syslog_ =
979 data_->num_chars_to_log_ - data_->num_prefix_chars_;
981 // Do we need to add a \n to the end of this message?
982 bool append_newline =
983 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
984 char original_final_char = '\0';
986 // If we do need to add a \n, we'll do it by violating the memory of the
987 // ostrstream buffer. This is quick, and we'll make sure to undo our
988 // modification before anything else is done with the ostrstream. It
989 // would be preferable not to do things this way, but it seems to be
990 // the best way to deal with this.
991 if (append_newline) {
992 original_final_char = data_->message_text_[data_->num_chars_to_log_];
993 data_->message_text_[data_->num_chars_to_log_++] = '\n';
996 // Prevent any subtle race conditions by wrapping a mutex lock around
997 // the actual logging action per se.
999 MutexLock l(&log_mutex);
1000 (this->*(data_->send_method_))();
1001 ++num_messages_[static_cast<int>(data_->severity_)];
1003 LogDestination::WaitForSinks(data_);
1005 if (append_newline) {
1006 // Fix the ostrstream back how it was before we screwed with it.
1007 // It's 99.44% certain that we don't need to worry about doing this.
1008 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1011 // If errno was already set before we enter the logging call, we'll
1012 // set it back to that value when we return from the logging call.
1013 // It happens often that we log an error message after a syscall
1014 // failure, which can potentially set the errno to some other
1015 // values. We would like to preserve the original errno.
1016 if (data_->preserved_errno_ != 0) {
1017 errno = data_->preserved_errno_;
1020 // Note that this message is now safely logged. If we're asked to flush
1021 // again, as a result of destruction, say, we'll do nothing on future calls.
1022 data_->has_been_flushed_ = true;
1025 // Copy of FATAL log message so that we can print it out again after
1026 // all the stack traces.
1027 // We cannot simply use fatal_message_buffer, because two or more FATAL log
1028 // messages may happen in a row. This is a real possibility given that
1029 // FATAL log messages are often associated with corrupted process state.
1030 // In this case, we still want to reprint the first FATAL log message, so
1031 // we need to save away the first message in a separate buffer.
1032 static time_t fatal_time;
1033 static char fatal_message[256];
1035 void ReprintFatalMessage() {
1036 if (fatal_message[0]) {
1037 const int n = strlen(fatal_message);
1038 if (!FLAGS_logtostderr) {
1039 // Also write to stderr
1040 WriteToStderr(fatal_message, n);
1042 LogDestination::LogToAllLogfiles(ERROR, fatal_time, fatal_message, n);
1046 // L >= log_mutex (callers must hold the log_mutex).
1047 void LogMessage::SendToLog() {
1048 static bool already_warned_before_initgoogle = false;
1050 log_mutex.AssertHeld();
1052 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1053 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1055 // Messages of a given severity get logged to lower severity logs, too
1057 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1058 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1059 "written to STDERR\n";
1060 WriteToStderr(w, strlen(w));
1061 already_warned_before_initgoogle = true;
1064 // global flag: never log to file if set. Also -- don't log to a
1065 // file if we haven't parsed the command line flags to get the
1067 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1068 WriteToStderr(data_->message_text_, data_->num_chars_to_log_);
1070 // this could be protected by a flag if necessary.
1071 LogDestination::LogToSinks(data_->severity_,
1072 data_->fullname_, data_->basename_,
1073 data_->line_, &data_->tm_time_,
1074 data_->message_text_ + data_->num_prefix_chars_,
1075 (data_->num_chars_to_log_ -
1076 data_->num_prefix_chars_ - 1));
1079 // log this message to all log files of severity <= severity_
1080 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1081 data_->message_text_,
1082 data_->num_chars_to_log_);
1084 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1085 data_->num_chars_to_log_);
1086 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1087 data_->num_chars_to_log_);
1088 LogDestination::LogToSinks(data_->severity_,
1089 data_->fullname_, data_->basename_,
1090 data_->line_, &data_->tm_time_,
1091 data_->message_text_ + data_->num_prefix_chars_,
1092 (data_->num_chars_to_log_
1093 - data_->num_prefix_chars_ - 1));
1094 // NOTE: -1 removes trailing \n
1097 // If we log a FATAL message, flush all the log destinations, then toss
1098 // a signal for others to catch. We leave the logs in a state that
1099 // someone else can use them (as long as they flush afterwards)
1100 if (data_->severity_ == FATAL) {
1101 // save away the fatal message so we can print it again later
1102 const int copy = min<int>(data_->num_chars_to_log_,
1103 sizeof(fatal_message)-1);
1104 memcpy(fatal_message, data_->message_text_, copy);
1105 fatal_message[copy] = '\0';
1106 fatal_time = data_->timestamp_;
1108 if (!FLAGS_logtostderr) {
1109 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1110 if ( LogDestination::log_destinations_[i] )
1111 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1115 // release the lock that our caller (directly or indirectly)
1116 // LogMessage::~LogMessage() grabbed so that signal handlers
1117 // can use the logging facility. Alternately, we could add
1118 // an entire unsafe logging interface to bypass locking
1119 // for signal handlers but this seems simpler.
1121 LogDestination::WaitForSinks(data_);
1127 static void logging_fail() {
1128 #if defined(_DEBUG) && defined(_MSC_VER)
1129 // When debugging on windows, avoid the obnoxious dialog and make
1130 // it possible to continue past a LOG(FATAL) in the debugger
1137 #ifdef HAVE___ATTRIBUTE__
1138 GOOGLE_GLOG_DLL_DECL
1139 void (*g_logging_fail_func)() __attribute__((noreturn)) = &logging_fail;
1141 GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)() = &logging_fail;
1144 void InstallFailureFunction(void (*fail_func)()) {
1145 g_logging_fail_func = fail_func;
1148 void LogMessage::Fail() {
1149 g_logging_fail_func();
1152 // L >= log_mutex (callers must hold the log_mutex).
1153 void LogMessage::SendToSinkAndLog() {
1154 if (data_->sink_ != NULL) {
1155 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1156 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1157 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1158 data_->line_, &data_->tm_time_,
1159 data_->message_text_ + data_->num_prefix_chars_,
1160 (data_->num_chars_to_log_ -
1161 data_->num_prefix_chars_ - 1));
1166 // L >= log_mutex (callers must hold the log_mutex).
1167 void LogMessage::SaveOrSendToLog() {
1168 if (data_->outvec_ != NULL) {
1169 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1170 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1171 // Omit prefix of message and trailing newline when recording in outvec_.
1172 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1173 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1174 data_->outvec_->push_back(string(start, len));
1180 // L >= log_mutex (callers must hold the log_mutex).
1181 void LogMessage::SendToSyslogAndLog() {
1182 #ifdef HAVE_SYSLOG_H
1183 // Before any calls to syslog(), make a single call to openlog()
1184 static bool openlog_already_called = false;
1185 if (!openlog_already_called) {
1186 openlog(ProgramInvocationShortName(), LOG_CONS | LOG_NDELAY | LOG_PID,
1188 openlog_already_called = true;
1191 // This array maps Google severity levels to syslog levels
1192 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1193 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1194 int(data_->num_chars_to_syslog_),
1195 data_->message_text_ + data_->num_prefix_chars_);
1198 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1202 base::Logger* base::GetLogger(LogSeverity severity) {
1203 MutexLock l(&log_mutex);
1204 return LogDestination::log_destination(severity)->logger_;
1207 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1208 MutexLock l(&log_mutex);
1209 LogDestination::log_destination(severity)->logger_ = logger;
1212 // L < log_mutex. Acquires and releases mutex_.
1213 int64 LogMessage::num_messages(int severity) {
1214 MutexLock l(&log_mutex);
1215 return num_messages_[severity];
1218 // Output the COUNTER value. This is only valid if ostream is a
1220 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1221 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1222 CHECK(log == log->self());
1227 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1228 LogSeverity severity, int ctr,
1229 void (LogMessage::*send_method)())
1230 : LogMessage(file, line, severity, ctr, send_method) {
1233 ErrnoLogMessage::~ErrnoLogMessage() {
1234 // Don't access errno directly because it may have been altered
1235 // while streaming the message.
1237 posix_strerror_r(preserved_errno(), buf, sizeof(buf));
1238 stream() << ": " << buf << " [" << preserved_errno() << "]";
1241 void FlushLogFiles(LogSeverity min_severity) {
1242 LogDestination::FlushLogFiles(min_severity);
1245 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1246 LogDestination::FlushLogFilesUnsafe(min_severity);
1249 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1250 LogDestination::SetLogDestination(severity, base_filename);
1253 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1254 LogDestination::SetLogSymlink(severity, symlink_basename);
1257 LogSink::~LogSink() {
1260 void LogSink::WaitTillSent() {
1264 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1265 const struct ::tm* tm_time,
1266 const char* message, size_t message_len) {
1267 ostringstream stream(string(message, message_len));
1270 if ( is_default_thread() ) {
1271 stream << LogSeverityNames[severity][0]
1272 << setw(2) << 1+tm_time->tm_mon
1273 << setw(2) << tm_time->tm_mday
1275 << setw(2) << tm_time->tm_hour
1276 << setw(2) << tm_time->tm_min
1277 << setw(2) << tm_time->tm_sec
1278 << ' ' << file << ':' << line << "] ";
1280 stream << LogSeverityNames[severity][0]
1281 << setw(2) << 1+tm_time->tm_mon
1282 << setw(2) << tm_time->tm_mday
1284 << setw(2) << tm_time->tm_hour
1285 << setw(2) << tm_time->tm_min
1286 << setw(2) << tm_time->tm_sec
1287 << ' ' << setw(8) << std::hex << pthread_self() << std::dec
1288 << ' ' << file << ':' << line << "] ";
1291 stream << string(message, message_len);
1292 return stream.str();
1295 void AddLogSink(LogSink *destination) {
1296 LogDestination::AddLogSink(destination);
1299 void RemoveLogSink(LogSink *destination) {
1300 LogDestination::RemoveLogSink(destination);
1303 void SetLogFilenameExtension(const char* ext) {
1304 LogDestination::SetLogFilenameExtension(ext);
1307 void SetStderrLogging(LogSeverity min_severity) {
1308 LogDestination::SetStderrLogging(min_severity);
1311 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1312 LogDestination::SetEmailLogging(min_severity, addresses);
1315 void LogToStderr() {
1316 LogDestination::LogToStderr();
1319 // use_logging controls whether the logging functions LOG/VLOG are used
1320 // to log errors. It should be set to false when the caller holds the
1322 static bool SendEmailInternal(const char*dest, const char *subject,
1323 const char*body, bool use_logging) {
1324 if (dest && *dest) {
1325 if ( use_logging ) {
1326 VLOG(1) << "Trying to send TITLE:" << subject
1327 << " BODY:" << body << " to " << dest;
1329 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1330 subject, body, dest);
1333 string cmd(FLAGS_logmailer);
1334 cmd = cmd + " -s\"" + string(subject) + "\" " + string(dest);
1335 FILE* pipe = popen(cmd.c_str(), "w");
1337 // Add the body if we have one
1339 fwrite(body, sizeof(char), strlen(body), pipe);
1340 bool ok = pclose(pipe) != -1;
1342 if ( use_logging ) {
1344 posix_strerror_r(errno, buf, sizeof(buf));
1345 LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf;
1348 posix_strerror_r(errno, buf, sizeof(buf));
1349 fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf);
1354 if ( use_logging ) {
1355 LOG(ERROR) << "Unable to send mail to " << dest;
1357 fprintf(stderr, "Unable to send mail to %s\n", dest);
1364 bool SendEmail(const char*dest, const char *subject, const char*body){
1365 return SendEmailInternal(dest, subject, body, true);
1368 static void GetTempDirectories(vector<string>* list) {
1371 // On windows we'll try to find a directory in this order:
1372 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1375 // C:/WINDOWS/ or C:/WINNT/
1378 if (GetTempPathA(MAX_PATH, tmp))
1379 list->push_back(tmp);
1380 list->push_back("C:\\tmp\\");
1381 list->push_back("C:\\temp\\");
1383 // Directories, in order of preference. If we find a dir that
1384 // exists, we stop adding other less-preferred dirs
1385 const char * candidates[] = {
1386 // Non-null only during unittest/regtest
1387 getenv("TEST_TMPDIR"),
1389 // Explicitly-supplied temp dirs
1390 getenv("TMPDIR"), getenv("TMP"),
1392 // If all else fails
1396 for (int i = 0; i < ARRAYSIZE(candidates); i++) {
1397 const char *d = candidates[i];
1398 if (!d) continue; // Empty env var
1400 // Make sure we don't surprise anyone who's expecting a '/'
1402 if (dstr[dstr.size() - 1] != '/') {
1405 list->push_back(dstr);
1407 struct stat statbuf;
1408 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1409 // We found a dir that exists - we're done.
1417 static vector<string>* logging_directories_list;
1419 const vector<string>& GetLoggingDirectories() {
1420 // Not strictly thread-safe but we're called early in InitGoogle().
1421 if (logging_directories_list == NULL) {
1422 logging_directories_list = new vector<string>;
1424 if ( !FLAGS_log_dir.empty() ) {
1425 // A dir was specified, we should use it
1426 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1428 GetTempDirectories(logging_directories_list);
1431 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1432 logging_directories_list->push_back(tmp);
1433 logging_directories_list->push_back(".\\");
1435 logging_directories_list->push_back("./");
1439 return *logging_directories_list;
1442 void TestOnly_ClearLoggingDirectoriesList() {
1443 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1444 "called from test code.\n");
1445 delete logging_directories_list;
1446 logging_directories_list = NULL;
1449 void GetExistingTempDirectories(vector<string>* list) {
1450 GetTempDirectories(list);
1451 vector<string>::iterator i_dir = list->begin();
1452 while( i_dir != list->end() ) {
1453 // zero arg to access means test for existence; no constant
1454 // defined on windows
1455 if ( access(i_dir->c_str(), 0) ) {
1456 i_dir = list->erase(i_dir);
1463 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1464 #ifdef HAVE_UNISTD_H
1465 struct stat statbuf;
1466 const int kCopyBlockSize = 8 << 10;
1467 char copybuf[kCopyBlockSize];
1468 int64 read_offset, write_offset;
1469 // Don't follow symlinks unless they're our own fd symlinks in /proc
1471 const char *procfd_prefix = "/proc/self/fd/";
1472 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1474 int fd = open(path, flags);
1476 if (errno == EFBIG) {
1477 // The log file in question has got too big for us to open. The
1478 // real fix for this would be to compile logging.cc (or probably
1479 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1481 // Instead just truncate the file to something we can manage
1482 if (truncate(path, 0) == -1) {
1483 PLOG(ERROR) << "Unable to truncate " << path;
1485 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1488 PLOG(ERROR) << "Unable to open " << path;
1493 if (fstat(fd, &statbuf) == -1) {
1494 PLOG(ERROR) << "Unable to fstat()";
1498 // See if the path refers to a regular file bigger than the
1500 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1501 if (statbuf.st_size <= limit) goto out_close_fd;
1502 if (statbuf.st_size <= keep) goto out_close_fd;
1504 // This log file is too large - we need to truncate it
1505 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1507 // Copy the last "keep" bytes of the file to the beginning of the file
1508 read_offset = statbuf.st_size - keep;
1510 int bytesin, bytesout;
1511 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1512 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1513 if (bytesout == -1) {
1514 PLOG(ERROR) << "Unable to write to " << path;
1516 } else if (bytesout != bytesin) {
1517 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1519 read_offset += bytesin;
1520 write_offset += bytesout;
1522 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1524 // Truncate the remainder of the file. If someone else writes to the
1525 // end of the file after our last read() above, we lose their latest
1526 // data. Too bad ...
1527 if (ftruncate(fd, write_offset) == -1) {
1528 PLOG(ERROR) << "Unable to truncate " << path;
1534 LOG(ERROR) << "No log truncation support.";
1538 void TruncateStdoutStderr() {
1539 #ifdef HAVE_UNISTD_H
1540 int64 limit = FLAGS_max_log_size << 20;
1541 int64 keep = 1 << 20;
1542 TruncateLogFile("/proc/self/fd/1", limit, keep);
1543 TruncateLogFile("/proc/self/fd/2", limit, keep);
1545 LOG(ERROR) << "No log truncation support.";
1550 // Helper functions for string comparisons.
1551 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1552 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1553 const char* names) { \
1554 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1555 if (equal == expected) return NULL; \
1560 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1561 return new string(ss.str(), ss.pcount()); \
1564 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1565 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1566 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1567 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1568 #undef DEFINE_CHECK_STROP_IMPL
1570 int posix_strerror_r(int err, char *buf, size_t len) {
1571 // Sanity check input parameters
1572 if (buf == NULL || len <= 0) {
1577 // Reset buf and errno, and try calling whatever version of strerror_r()
1578 // is implemented by glibc
1580 int old_errno = errno;
1582 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1584 // Both versions set errno on failure
1586 // Should already be there, but better safe than sorry
1592 // POSIX is vague about whether the string will be terminated, although
1593 // is indirectly implies that typically ERANGE will be returned, instead
1594 // of truncating the string. This is different from the GNU implementation.
1595 // We play it safe by always terminating the string explicitly.
1596 buf[len-1] = '\000';
1598 // If the function succeeded, we can use its exit code to determine the
1599 // semantics implemented by glibc
1603 // GNU semantics detected
1608 #if defined(OS_MACOSX) || defined(OS_FREEBSD)
1609 if (reinterpret_cast<int>(rc) < sys_nerr) {
1610 // This means an error on MacOSX or FreeBSD.
1614 strncat(buf, rc, len-1);
1620 LogMessageFatal::LogMessageFatal(const char* file, int line) :
1621 LogMessage(file, line, FATAL) {}
1623 LogMessageFatal::LogMessageFatal(const char* file, int line,
1624 const CheckOpString& result) :
1625 LogMessage(file, line, result) {}
1627 LogMessageFatal::~LogMessageFatal() {
1632 _END_GOOGLE_NAMESPACE_