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"
36 #ifdef HAVE_STACKTRACE
37 # include "stacktrace.h"
42 using std::ostrstream;
49 using std::ostringstream;
52 // There is no thread annotation support.
53 #define EXCLUSIVE_LOCKS_REQUIRED(mu)
55 static bool BoolFromEnv(const char *varname, bool defval) {
56 const char* const valstr = getenv(varname);
60 return memchr("tTyY1\0", valstr[0], 6) != NULL;
63 DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
64 "log messages go to stderr instead of logfiles");
65 DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
66 "log messages go to stderr in addition to logfiles");
68 DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
69 "Logs can grow very quickly and they are rarely read before they "
70 "need to be evicted from memory. Instead, drop them from memory "
71 "as soon as they are flushed to disk.");
72 _START_GOOGLE_NAMESPACE_
74 static const int64 kPageSize = getpagesize();
76 _END_GOOGLE_NAMESPACE_
79 // By default, errors (including fatal errors) get logged to stderr as
82 // The default is ERROR instead of FATAL so that users can see problems
83 // when they run a program without having to look in another file.
84 DEFINE_int32(stderrthreshold,
85 GOOGLE_NAMESPACE::ERROR,
86 "log messages at or above this level are copied to stderr in "
87 "addition to logfiles. This flag obsoletes --alsologtostderr.");
89 DEFINE_string(alsologtoemail, "",
90 "log messages go to these email addresses "
91 "in addition to logfiles");
92 DEFINE_bool(log_prefix, true,
93 "Prepend the log prefix to the start of each log line");
94 DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
95 "actually get logged anywhere");
96 DEFINE_int32(logbuflevel, 0,
97 "Buffer log messages logged at this level or lower"
98 " (-1 means don't buffer; 0 means buffer INFO only;"
100 DEFINE_int32(logbufsecs, 30,
101 "Buffer log messages for at most this many seconds");
102 DEFINE_int32(logemaillevel, 999,
103 "Email log messages logged at this level or higher"
104 " (0 means email all; 3 means email FATAL only;"
106 DEFINE_string(logmailer, "/bin/mail",
107 "Mailer used to send logging email");
109 // Compute the default value for --log_dir
110 static const char* DefaultLogDir() {
112 env = getenv("GOOGLE_LOG_DIR");
113 if (env != NULL && env[0] != '\0') {
116 env = getenv("TEST_TMPDIR");
117 if (env != NULL && env[0] != '\0') {
123 DEFINE_string(log_dir, DefaultLogDir(),
124 "If specified, logfiles are written into this directory instead "
125 "of the default logging directory.");
126 DEFINE_string(log_link, "", "Put additional links to the log "
127 "files in this directory");
129 DEFINE_int32(max_log_size, 1800,
130 "approx. maximum log file size (in MB). A value of 0 will "
131 "be silently overridden to 1.");
133 DEFINE_bool(stop_logging_if_full_disk, false,
134 "Stop attempting to log to disk if the disk is full.");
136 DEFINE_string(log_backtrace_at, "",
137 "Emit a backtrace when logging at file:linenum.");
139 // TODO(hamaji): consider windows
140 #define PATH_SEPARATOR '/'
142 static void GetHostName(string* hostname) {
143 #if defined(HAVE_SYS_UTSNAME_H)
145 if (0 != uname(&buf)) {
146 // ensure null termination on failure
147 *buf.nodename = '\0';
149 *hostname = buf.nodename;
150 #elif defined(OS_WINDOWS)
153 if (GetComputerNameA(buf, &len)) {
159 # warning There is no way to retrieve the host name.
160 *hostname = "(unknown)";
164 _START_GOOGLE_NAMESPACE_
166 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
167 static int32 MaxLogSize() {
168 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
171 // A mutex that allows only one thread to log at a time, to keep things from
172 // getting jumbled. Some other very uncommon logging operations (like
173 // changing the destination file for log messages of a given severity) also
174 // lock this mutex. Please be sure that anybody who might possibly need to
176 static Mutex log_mutex;
178 // Number of messages sent at each severity. Under log_mutex.
179 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
181 // Globally disable log writing (if disk is full)
182 static bool stop_writing = false;
184 const char*const LogSeverityNames[NUM_SEVERITIES] = {
185 "INFO", "WARNING", "ERROR", "FATAL"
188 // Has the user called SetExitOnDFatal(true)?
189 static bool exit_on_dfatal = true;
191 const char* GetLogSeverityName(LogSeverity severity) {
192 return LogSeverityNames[severity];
195 static bool SendEmailInternal(const char*dest, const char *subject,
196 const char*body, bool use_logging);
198 base::Logger::~Logger() {
203 // Encapsulates all file-system related state
204 class LogFileObject : public base::Logger {
206 LogFileObject(LogSeverity severity, const char* base_filename);
209 virtual void Write(bool force_flush, // Should we force a flush here?
210 time_t timestamp, // Timestamp for this entry
214 // Configuration options
215 void SetBasename(const char* basename);
216 void SetExtension(const char* ext);
217 void SetSymlinkBasename(const char* symlink_basename);
219 // Normal flushing routine
220 virtual void Flush();
222 // It is the actual file length for the system loggers,
223 // i.e., INFO, ERROR, etc.
224 virtual uint32 LogSize() {
229 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
230 // can avoid grabbing a lock. Usually Flush() calls it after
232 void FlushUnlocked();
235 static const uint32 kRolloverAttemptFrequency = 0x20;
238 bool base_filename_selected_;
239 string base_filename_;
240 string symlink_basename_;
241 string filename_extension_; // option users can specify (eg to add port#)
243 LogSeverity severity_;
244 uint32 bytes_since_flush_;
246 unsigned int rollover_attempt_;
247 int64 next_flush_time_; // cycle count at which to flush log
249 // Actually create a logfile using the value of base_filename_ and the
250 // supplied argument time_pid_string
251 // REQUIRES: lock_ is held
252 bool CreateLogfile(const char* time_pid_string);
257 class LogDestination {
259 friend class LogMessage;
260 friend void ReprintFatalMessage();
261 friend base::Logger* base::GetLogger(LogSeverity);
262 friend void base::SetLogger(LogSeverity, base::Logger*);
264 // These methods are just forwarded to by their global versions.
265 static void SetLogDestination(LogSeverity severity,
266 const char* base_filename);
267 static void SetLogSymlink(LogSeverity severity,
268 const char* symlink_basename);
269 static void AddLogSink(LogSink *destination);
270 static void RemoveLogSink(LogSink *destination);
271 static void SetLogFilenameExtension(const char* filename_extension);
272 static void SetStderrLogging(LogSeverity min_severity);
273 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
274 static void LogToStderr();
275 // Flush all log files that are at least at the given severity level
276 static void FlushLogFiles(int min_severity);
277 static void FlushLogFilesUnsafe(int min_severity);
279 // we set the maximum size of our packet to be 1400, the logic being
280 // to prevent fragmentation.
281 // Really this number is arbitrary.
282 static const int kNetworkBytes = 1400;
284 static const string& hostname();
287 LogDestination(LogSeverity severity, const char* base_filename);
288 ~LogDestination() { }
290 // Take a log message of a particular severity and log it to stderr
291 // iff it's of a high enough severity to deserve it.
292 static void MaybeLogToStderr(LogSeverity severity, const char* message,
295 // Take a log message of a particular severity and log it to email
296 // iff it's of a high enough severity to deserve it.
297 static void MaybeLogToEmail(LogSeverity severity, const char* message,
299 // Take a log message of a particular severity and log it to a file
300 // iff the base filename is not "" (which means "don't log to me")
301 static void MaybeLogToLogfile(LogSeverity severity,
303 const char* message, size_t len);
304 // Take a log message of a particular severity and log it to the file
305 // for that severity and also for all files with severity less than
307 static void LogToAllLogfiles(LogSeverity severity,
309 const char* message, size_t len);
311 // Send logging info to all registered sinks.
312 static void LogToSinks(LogSeverity severity,
313 const char *full_filename,
314 const char *base_filename,
316 const struct ::tm* tm_time,
320 // Wait for all registered sinks via WaitTillSent
321 // including the optional one in "data".
322 static void WaitForSinks(LogMessage::LogMessageData* data);
324 static LogDestination* log_destination(LogSeverity severity);
326 LogFileObject fileobject_;
327 base::Logger* logger_; // Either &fileobject_, or wrapper around it
329 static LogDestination* log_destinations_[NUM_SEVERITIES];
330 static LogSeverity email_logging_severity_;
331 static string addresses_;
332 static string hostname_;
334 // arbitrary global logging destinations.
335 static vector<LogSink*>* sinks_;
337 // Protects the vector sinks_,
338 // but not the LogSink objects its elements reference.
339 static Mutex sink_mutex_;
342 LogDestination(const LogDestination&);
343 LogDestination& operator=(const LogDestination&);
346 // Errors do not get logged to email by default.
347 LogSeverity LogDestination::email_logging_severity_ = 99999;
349 string LogDestination::addresses_;
350 string LogDestination::hostname_;
352 vector<LogSink*>* LogDestination::sinks_ = NULL;
353 Mutex LogDestination::sink_mutex_;
356 const string& LogDestination::hostname() {
357 if (hostname_.empty()) {
358 GetHostName(&hostname_);
359 if (hostname_.empty()) {
360 hostname_ = "(unknown)";
366 LogDestination::LogDestination(LogSeverity severity,
367 const char* base_filename)
368 : fileobject_(severity, base_filename),
369 logger_(&fileobject_) {
372 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
373 // assume we have the log_mutex or we simply don't care
375 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
376 LogDestination* log = log_destination(i);
378 // Flush the base fileobject_ logger directly instead of going
379 // through any wrappers to reduce chance of deadlock.
380 log->fileobject_.FlushUnlocked();
385 inline void LogDestination::FlushLogFiles(int min_severity) {
386 // Prevent any subtle race conditions by wrapping a mutex lock around
388 MutexLock l(&log_mutex);
389 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
390 LogDestination* log = log_destination(i);
392 log->logger_->Flush();
397 inline void LogDestination::SetLogDestination(LogSeverity severity,
398 const char* base_filename) {
399 assert(severity >= 0 && severity < NUM_SEVERITIES);
400 // Prevent any subtle race conditions by wrapping a mutex lock around
402 MutexLock l(&log_mutex);
403 log_destination(severity)->fileobject_.SetBasename(base_filename);
406 inline void LogDestination::SetLogSymlink(LogSeverity severity,
407 const char* symlink_basename) {
408 CHECK_GE(severity, 0);
409 CHECK_LT(severity, NUM_SEVERITIES);
410 MutexLock l(&log_mutex);
411 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
414 inline void LogDestination::AddLogSink(LogSink *destination) {
415 // Prevent any subtle race conditions by wrapping a mutex lock around
417 MutexLock l(&sink_mutex_);
418 if (!sinks_) sinks_ = new vector<LogSink*>;
419 sinks_->push_back(destination);
422 inline void LogDestination::RemoveLogSink(LogSink *destination) {
423 // Prevent any subtle race conditions by wrapping a mutex lock around
425 MutexLock l(&sink_mutex_);
426 // This doesn't keep the sinks in order, but who cares?
428 for (int i = sinks_->size() - 1; i >= 0; i--) {
429 if ((*sinks_)[i] == destination) {
430 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
438 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
439 // Prevent any subtle race conditions by wrapping a mutex lock around
441 MutexLock l(&log_mutex);
442 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
443 log_destination(severity)->fileobject_.SetExtension(ext);
447 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
448 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
449 // Prevent any subtle race conditions by wrapping a mutex lock around
451 MutexLock l(&log_mutex);
452 FLAGS_stderrthreshold = min_severity;
455 inline void LogDestination::LogToStderr() {
456 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
457 // SetLogDestination already do the locking!
458 SetStderrLogging(0); // thus everything is "also" logged to stderr
459 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
460 SetLogDestination(i, ""); // "" turns off logging to a logfile
464 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
465 const char* addresses) {
466 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
467 // Prevent any subtle race conditions by wrapping a mutex lock around
469 MutexLock l(&log_mutex);
470 LogDestination::email_logging_severity_ = min_severity;
471 LogDestination::addresses_ = addresses;
474 static void WriteToStderr(const char* message, size_t len) {
475 // Avoid using cerr from this module since we may get called during
476 // exit code, and cerr may be partially or fully destroyed by then.
477 write(STDERR_FILENO, message, len);
480 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
481 const char* message, size_t len) {
482 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
483 WriteToStderr(message, len);
485 // On Windows, also output to the debugger
486 ::OutputDebugStringA(string(message,len).c_str());
492 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
493 const char* message, size_t len) {
494 if (severity >= email_logging_severity_ ||
495 severity >= FLAGS_logemaillevel) {
496 string to(FLAGS_alsologtoemail);
497 if (!addresses_.empty()) {
503 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
504 ProgramInvocationShortName());
505 string body(hostname());
507 body.append(message, len);
509 // should NOT use SendEmail(). The caller of this function holds the
510 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
511 // acquire the log_mutex object. Use SendEmailInternal() and set
512 // use_logging to false.
513 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
518 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
522 const bool should_flush = severity > FLAGS_logbuflevel;
523 LogDestination* destination = log_destination(severity);
524 destination->logger_->Write(should_flush, timestamp, message, len);
527 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
532 if ( FLAGS_logtostderr ) // global flag: never log to file
533 WriteToStderr(message, len);
535 for (int i = severity; i >= 0; --i)
536 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
540 inline void LogDestination::LogToSinks(LogSeverity severity,
541 const char *full_filename,
542 const char *base_filename,
544 const struct ::tm* tm_time,
546 size_t message_len) {
547 ReaderMutexLock l(&sink_mutex_);
549 for (int i = sinks_->size() - 1; i >= 0; i--) {
550 (*sinks_)[i]->send(severity, full_filename, base_filename,
551 line, tm_time, message, message_len);
556 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
557 ReaderMutexLock l(&sink_mutex_);
559 for (int i = sinks_->size() - 1; i >= 0; i--) {
560 (*sinks_)[i]->WaitTillSent();
563 const bool send_to_sink =
564 (data->send_method_ == &LogMessage::SendToSink) ||
565 (data->send_method_ == &LogMessage::SendToSinkAndLog);
566 if (send_to_sink && data->sink_ != NULL) {
567 data->sink_->WaitTillSent();
571 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
573 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
574 assert(severity >=0 && severity < NUM_SEVERITIES);
575 if (!log_destinations_[severity]) {
576 log_destinations_[severity] = new LogDestination(severity, NULL);
578 return log_destinations_[severity];
583 LogFileObject::LogFileObject(LogSeverity severity,
584 const char* base_filename)
585 : base_filename_selected_(base_filename != NULL),
586 base_filename_((base_filename != NULL) ? base_filename : ""),
587 symlink_basename_(ProgramInvocationShortName()),
588 filename_extension_(),
591 bytes_since_flush_(0),
593 rollover_attempt_(kRolloverAttemptFrequency-1),
594 next_flush_time_(0) {
595 assert(severity >= 0);
596 assert(severity < NUM_SEVERITIES);
599 LogFileObject::~LogFileObject() {
607 void LogFileObject::SetBasename(const char* basename) {
609 base_filename_selected_ = true;
610 if (base_filename_ != basename) {
611 // Get rid of old log file since we are changing names
615 rollover_attempt_ = kRolloverAttemptFrequency-1;
617 base_filename_ = basename;
621 void LogFileObject::SetExtension(const char* ext) {
623 if (filename_extension_ != ext) {
624 // Get rid of old log file since we are changing names
628 rollover_attempt_ = kRolloverAttemptFrequency-1;
630 filename_extension_ = ext;
634 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
636 symlink_basename_ = symlink_basename;
639 void LogFileObject::Flush() {
644 void LogFileObject::FlushUnlocked(){
647 bytes_since_flush_ = 0;
649 // Figure out when we are due for another flush.
650 const int64 next = (FLAGS_logbufsecs
651 * static_cast<int64>(1000000)); // in usec
652 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
655 bool LogFileObject::CreateLogfile(const char* time_pid_string) {
656 string string_filename = base_filename_+filename_extension_+
658 const char* filename = string_filename.c_str();
659 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
660 if (fd == -1) return false;
662 // Mark the file close-on-exec. We don't really care if this fails
663 fcntl(fd, F_SETFD, FD_CLOEXEC);
666 file_ = fdopen(fd, "a"); // Make a FILE*.
667 if (file_ == NULL) { // Man, we're screwed!
669 unlink(filename); // Erase the half-baked evidence: an unusable log file
673 // We try to create a symlink called <program_name>.<severity>,
674 // which is easier to use. (Every time we create a new logfile,
675 // we destroy the old symlink and create a new one, so it always
676 // points to the latest logfile.) If it fails, we're sad but it's
678 if (!symlink_basename_.empty()) {
679 // take directory from filename
680 const char* slash = strrchr(filename, PATH_SEPARATOR);
681 const string linkname =
682 symlink_basename_ + '.' + LogSeverityNames[severity_];
684 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
685 linkpath += linkname;
686 unlink(linkpath.c_str()); // delete old one if it exists
688 // We must have unistd.h.
690 // Make the symlink be relative (in the same dir) so that if the
691 // entire log directory gets relocated the link is still valid.
692 const char *linkdest = slash ? (slash + 1) : filename;
693 symlink(linkdest, linkpath.c_str()); // silently ignore failures
695 // Make an additional link to the log file in a place specified by
696 // FLAGS_log_link, if indicated
697 if (!FLAGS_log_link.empty()) {
698 linkpath = FLAGS_log_link + "/" + linkname;
699 unlink(linkpath.c_str()); // delete old one if it exists
700 symlink(filename, linkpath.c_str()); // silently ignore failures
705 return true; // Everything worked
708 void LogFileObject::Write(bool force_flush,
714 // We don't log if the base_name_ is "" (which means "don't write")
715 if (base_filename_selected_ && base_filename_.empty()) {
719 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize()) {
720 if (file_ != NULL) fclose(file_);
722 file_length_ = bytes_since_flush_ = 0;
723 rollover_attempt_ = kRolloverAttemptFrequency-1;
726 // If there's no destination file, make one before outputting
728 // Try to rollover the log file every 32 log messages. The only time
729 // this could matter would be when we have trouble creating the log
730 // file. If that happens, we'll lose lots of log messages, of course!
731 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
732 rollover_attempt_ = 0;
735 localtime_r(×tamp, &tm_time);
737 // The logfile's filename will have the date/time & pid in it
738 char time_pid_string[256]; // More than enough chars for time, pid, \0
739 ostrstream time_pid_stream(time_pid_string, sizeof(time_pid_string));
740 time_pid_stream.fill('0');
741 time_pid_stream << 1900+tm_time.tm_year
742 << setw(2) << 1+tm_time.tm_mon
743 << setw(2) << tm_time.tm_mday
745 << setw(2) << tm_time.tm_hour
746 << setw(2) << tm_time.tm_min
747 << setw(2) << tm_time.tm_sec
749 << GetMainThreadPid()
752 if (base_filename_selected_) {
753 if (!CreateLogfile(time_pid_string)) {
754 perror("Could not create log file");
755 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", time_pid_string);
759 // If no base filename for logs of this severity has been set, use a
760 // default base filename of
761 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
762 // logfiles will have names like
763 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
764 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
765 // and 4354 is the pid of the logging process. The date & time reflect
766 // when the file was created for output.
768 // Where does the file get put? Successively try the directories
770 string stripped_filename(ProgramInvocationShortName()); // in cmdlineflag
772 GetHostName(&hostname);
774 string uidname = MyUserName();
775 // We should not call CHECK() here because this function can be
776 // called after holding on to log_mutex. We don't want to
777 // attempt to hold on to the same mutex, and get into a
778 // deadlock. Simply use a name like invalid-user.
779 if (uidname.empty()) uidname = "invalid-user";
781 stripped_filename = stripped_filename+'.'+hostname+'.'
783 +LogSeverityNames[severity_]+'.';
784 // We're going to (potentially) try to put logs in several different dirs
785 const vector<string> & log_dirs = GetLoggingDirectories();
787 // Go through the list of dirs, and try to create the log file in each
788 // until we succeed or run out of options
789 bool success = false;
790 for (vector<string>::const_iterator dir = log_dirs.begin();
791 dir != log_dirs.end();
793 base_filename_ = *dir + "/" + stripped_filename;
794 if ( CreateLogfile(time_pid_string) ) {
799 // If we never succeeded, we have to give up
800 if ( success == false ) {
801 perror("Could not create logging file");
802 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", time_pid_string);
807 // Write a header message into the log file
808 char file_header_string[512]; // Enough chars for time and binary info
809 ostrstream file_header_stream(file_header_string,
810 sizeof(file_header_string));
811 file_header_stream.fill('0');
812 file_header_stream << "Log file created at: "
813 << 1900+tm_time.tm_year << '/'
814 << setw(2) << 1+tm_time.tm_mon << '/'
815 << setw(2) << tm_time.tm_mday
817 << setw(2) << tm_time.tm_hour << ':'
818 << setw(2) << tm_time.tm_min << ':'
819 << setw(2) << tm_time.tm_sec << '\n'
820 << "Running on machine: "
821 << LogDestination::hostname() << '\n'
822 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
823 << "threadid file:line] msg" << '\n'
825 int header_len = strlen(file_header_string);
826 fwrite(file_header_string, 1, header_len, file_);
827 file_length_ += header_len;
828 bytes_since_flush_ += header_len;
832 if ( !stop_writing ) {
833 // fwrite() doesn't return an error when the disk is full, for
834 // messages that are less than 4096 bytes. When the disk is full,
835 // it returns the message length for messages that are less than
836 // 4096 bytes. fwrite() returns 4096 for message lengths that are
837 // greater than 4096, thereby indicating an error.
839 fwrite(message, 1, message_len, file_);
840 if ( FLAGS_stop_logging_if_full_disk &&
841 errno == ENOSPC ) { // disk full, stop writing to disk
842 stop_writing = true; // until the disk is
845 file_length_ += message_len;
846 bytes_since_flush_ += message_len;
849 if ( CycleClock_Now() >= next_flush_time_ )
850 stop_writing = false; // check to see if disk has free space.
851 return; // no need to flush
854 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
855 // or every "FLAGS_logbufsecs" seconds.
857 (bytes_since_flush_ >= 1000000) ||
858 (CycleClock_Now() >= next_flush_time_) ) {
861 if (FLAGS_drop_log_memory) {
862 if (file_length_ >= logging::kPageSize) {
863 // don't evict the most recent page
864 uint32 len = file_length_ & ~(logging::kPageSize - 1);
865 posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
874 // An arbitrary limit on the length of a single log message. This
875 // is so that streaming can be done more efficiently.
876 const size_t LogMessage::kMaxLogMessageLen = 30000;
878 // Static log data space to avoid alloc failures in a LOG(FATAL)
880 // Since multiple threads may call LOG(FATAL), and we want to preserve
881 // the data from the first call, we allocate two sets of space. One
882 // for exclusive use by the first thread, and one for shared use by
883 // all other threads.
884 static Mutex fatal_msg_lock;
885 static CrashReason crash_reason;
886 static bool fatal_msg_exclusive = true;
887 static char fatal_msg_buf_exclusive[LogMessage::kMaxLogMessageLen+1];
888 static char fatal_msg_buf_shared[LogMessage::kMaxLogMessageLen+1];
889 static LogMessage::LogStream fatal_msg_stream_exclusive(
890 fatal_msg_buf_exclusive, LogMessage::kMaxLogMessageLen, 0);
891 static LogMessage::LogStream fatal_msg_stream_shared(
892 fatal_msg_buf_shared, LogMessage::kMaxLogMessageLen, 0);
893 LogMessage::LogMessageData LogMessage::fatal_msg_data_exclusive_;
894 LogMessage::LogMessageData LogMessage::fatal_msg_data_shared_;
896 LogMessage::LogMessageData::~LogMessageData() {
898 delete stream_alloc_;
901 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
902 int ctr, void (LogMessage::*send_method)()) {
903 Init(file, line, severity, send_method);
904 data_->stream_->set_ctr(ctr);
907 LogMessage::LogMessage(const char* file, int line,
908 const CheckOpString& result) {
909 Init(file, line, FATAL, &LogMessage::SendToLog);
910 stream() << "Check failed: " << (*result.str_) << " ";
913 LogMessage::LogMessage(const char* file, int line) {
914 Init(file, line, INFO, &LogMessage::SendToLog);
917 LogMessage::LogMessage(const char* file, int line, LogSeverity severity) {
918 Init(file, line, severity, &LogMessage::SendToLog);
921 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
922 LogSink* sink, bool also_send_to_log) {
923 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
924 &LogMessage::SendToSink);
925 data_->sink_ = sink; // override Init()'s setting to NULL
928 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
929 vector<string> *outvec) {
930 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
931 data_->outvec_ = outvec; // override Init()'s setting to NULL
934 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
936 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
937 data_->message_ = message; // override Init()'s setting to NULL
940 void LogMessage::Init(const char* file,
942 LogSeverity severity,
943 void (LogMessage::*send_method)()) {
945 if (severity != FATAL || !exit_on_dfatal) {
946 allocated_ = new LogMessageData();
948 data_->buf_ = new char[kMaxLogMessageLen+1];
949 data_->message_text_ = data_->buf_;
950 data_->stream_alloc_ =
951 new LogStream(data_->message_text_, kMaxLogMessageLen, 0);
952 data_->stream_ = data_->stream_alloc_;
953 data_->first_fatal_ = false;
955 MutexLock l(&fatal_msg_lock);
956 if (fatal_msg_exclusive) {
957 fatal_msg_exclusive = false;
958 data_ = &fatal_msg_data_exclusive_;
959 data_->message_text_ = fatal_msg_buf_exclusive;
960 data_->stream_ = &fatal_msg_stream_exclusive;
961 data_->first_fatal_ = true;
963 data_ = &fatal_msg_data_shared_;
964 data_->message_text_ = fatal_msg_buf_shared;
965 data_->stream_ = &fatal_msg_stream_shared;
966 data_->first_fatal_ = false;
968 data_->stream_alloc_ = NULL;
972 data_->preserved_errno_ = errno;
973 data_->severity_ = severity;
975 data_->send_method_ = send_method;
977 data_->outvec_ = NULL;
978 WallTime now = WallTime_Now();
979 data_->timestamp_ = static_cast<time_t>(now);
980 localtime_r(&data_->timestamp_, &data_->tm_time_);
981 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
982 RawLog__SetLastTime(data_->tm_time_, usecs);
984 data_->num_chars_to_log_ = 0;
985 data_->num_chars_to_syslog_ = 0;
986 data_->basename_ = const_basename(file);
987 data_->fullname_ = file;
988 data_->has_been_flushed_ = false;
990 // If specified, prepend a prefix to each line. For example:
991 // I1018 160715 f5d4fbb0 logging.cc:1153]
992 // (log level, GMT month, date, time, thread_id, file basename, line)
993 // We exclude the thread_id for the default thread.
994 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
995 stream() << LogSeverityNames[severity][0]
996 << setw(2) << 1+data_->tm_time_.tm_mon
997 << setw(2) << data_->tm_time_.tm_mday
999 << setw(2) << data_->tm_time_.tm_hour << ':'
1000 << setw(2) << data_->tm_time_.tm_min << ':'
1001 << setw(2) << data_->tm_time_.tm_sec << "."
1004 << setfill(' ') << setw(5)
1005 << static_cast<unsigned int>(GetTID()) << setfill('0')
1007 << data_->basename_ << ':' << data_->line_ << "] ";
1009 data_->num_prefix_chars_ = data_->stream_->pcount();
1011 if (!FLAGS_log_backtrace_at.empty()) {
1013 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1014 #ifdef HAVE_STACKTRACE
1015 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1017 DumpStackTraceToString(&stacktrace);
1018 stream() << " (stacktrace:\n" << stacktrace << ") ";
1024 LogMessage::~LogMessage() {
1029 // Flush buffered message, called by the destructor, or any other function
1030 // that needs to synchronize the log.
1031 void LogMessage::Flush() {
1032 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1035 data_->num_chars_to_log_ = data_->stream_->pcount();
1036 data_->num_chars_to_syslog_ =
1037 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1039 // Do we need to add a \n to the end of this message?
1040 bool append_newline =
1041 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1042 char original_final_char = '\0';
1044 // If we do need to add a \n, we'll do it by violating the memory of the
1045 // ostrstream buffer. This is quick, and we'll make sure to undo our
1046 // modification before anything else is done with the ostrstream. It
1047 // would be preferable not to do things this way, but it seems to be
1048 // the best way to deal with this.
1049 if (append_newline) {
1050 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1051 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1054 // Prevent any subtle race conditions by wrapping a mutex lock around
1055 // the actual logging action per se.
1057 MutexLock l(&log_mutex);
1058 (this->*(data_->send_method_))();
1059 ++num_messages_[static_cast<int>(data_->severity_)];
1061 LogDestination::WaitForSinks(data_);
1063 if (append_newline) {
1064 // Fix the ostrstream back how it was before we screwed with it.
1065 // It's 99.44% certain that we don't need to worry about doing this.
1066 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1069 // If errno was already set before we enter the logging call, we'll
1070 // set it back to that value when we return from the logging call.
1071 // It happens often that we log an error message after a syscall
1072 // failure, which can potentially set the errno to some other
1073 // values. We would like to preserve the original errno.
1074 if (data_->preserved_errno_ != 0) {
1075 errno = data_->preserved_errno_;
1078 // Note that this message is now safely logged. If we're asked to flush
1079 // again, as a result of destruction, say, we'll do nothing on future calls.
1080 data_->has_been_flushed_ = true;
1083 // Copy of first FATAL log message so that we can print it out again
1084 // after all the stack traces. To preserve legacy behavior, we don't
1085 // use fatal_msg_buf_exclusive.
1086 static time_t fatal_time;
1087 static char fatal_message[256];
1089 void ReprintFatalMessage() {
1090 if (fatal_message[0]) {
1091 const int n = strlen(fatal_message);
1092 if (!FLAGS_logtostderr) {
1093 // Also write to stderr
1094 WriteToStderr(fatal_message, n);
1096 LogDestination::LogToAllLogfiles(ERROR, fatal_time, fatal_message, n);
1100 // L >= log_mutex (callers must hold the log_mutex).
1101 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1102 static bool already_warned_before_initgoogle = false;
1104 log_mutex.AssertHeld();
1106 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1107 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1109 // Messages of a given severity get logged to lower severity logs, too
1111 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1112 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1113 "written to STDERR\n";
1114 WriteToStderr(w, strlen(w));
1115 already_warned_before_initgoogle = true;
1118 // global flag: never log to file if set. Also -- don't log to a
1119 // file if we haven't parsed the command line flags to get the
1121 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1122 WriteToStderr(data_->message_text_, data_->num_chars_to_log_);
1124 // this could be protected by a flag if necessary.
1125 LogDestination::LogToSinks(data_->severity_,
1126 data_->fullname_, data_->basename_,
1127 data_->line_, &data_->tm_time_,
1128 data_->message_text_ + data_->num_prefix_chars_,
1129 (data_->num_chars_to_log_ -
1130 data_->num_prefix_chars_ - 1));
1133 // log this message to all log files of severity <= severity_
1134 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1135 data_->message_text_,
1136 data_->num_chars_to_log_);
1138 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1139 data_->num_chars_to_log_);
1140 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1141 data_->num_chars_to_log_);
1142 LogDestination::LogToSinks(data_->severity_,
1143 data_->fullname_, data_->basename_,
1144 data_->line_, &data_->tm_time_,
1145 data_->message_text_ + data_->num_prefix_chars_,
1146 (data_->num_chars_to_log_
1147 - data_->num_prefix_chars_ - 1));
1148 // NOTE: -1 removes trailing \n
1151 // If we log a FATAL message, flush all the log destinations, then toss
1152 // a signal for others to catch. We leave the logs in a state that
1153 // someone else can use them (as long as they flush afterwards)
1154 if (data_->severity_ == FATAL && exit_on_dfatal) {
1155 if (data_->first_fatal_) {
1156 crash_reason.filename = fatal_msg_data_exclusive_.fullname_;
1157 crash_reason.line_number = fatal_msg_data_exclusive_.line_;
1158 crash_reason.message = fatal_msg_buf_exclusive +
1159 fatal_msg_data_exclusive_.num_prefix_chars_;
1160 #ifdef HAVE_STACKTRACE
1161 crash_reason.depth = GetStackTrace(crash_reason.stack,
1162 ARRAYSIZE(crash_reason.stack),
1165 crash_reason.depth = 0;
1167 SetCrashReason(&crash_reason);
1169 // Store shortened fatal message for other logs and GWQ status
1170 const int copy = min<int>(data_->num_chars_to_log_,
1171 sizeof(fatal_message)-1);
1172 memcpy(fatal_message, data_->message_text_, copy);
1173 fatal_message[copy] = '\0';
1174 fatal_time = data_->timestamp_;
1177 if (!FLAGS_logtostderr) {
1178 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1179 if ( LogDestination::log_destinations_[i] )
1180 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1184 // release the lock that our caller (directly or indirectly)
1185 // LogMessage::~LogMessage() grabbed so that signal handlers
1186 // can use the logging facility. Alternately, we could add
1187 // an entire unsafe logging interface to bypass locking
1188 // for signal handlers but this seems simpler.
1190 LogDestination::WaitForSinks(data_);
1192 const char* message = "*** Check failure stack trace: ***\n";
1193 write(STDERR_FILENO, message, strlen(message));
1198 static void logging_fail() {
1199 #if defined(_DEBUG) && defined(_MSC_VER)
1200 // When debugging on windows, avoid the obnoxious dialog and make
1201 // it possible to continue past a LOG(FATAL) in the debugger
1208 #ifdef HAVE___ATTRIBUTE__
1209 GOOGLE_GLOG_DLL_DECL
1210 void (*g_logging_fail_func)() __attribute__((noreturn)) = &logging_fail;
1212 GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)() = &logging_fail;
1215 void InstallFailureFunction(void (*fail_func)()) {
1216 g_logging_fail_func = fail_func;
1219 void LogMessage::Fail() {
1220 g_logging_fail_func();
1223 // L >= log_mutex (callers must hold the log_mutex).
1224 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1225 if (data_->sink_ != NULL) {
1226 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1227 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1228 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1229 data_->line_, &data_->tm_time_,
1230 data_->message_text_ + data_->num_prefix_chars_,
1231 (data_->num_chars_to_log_ -
1232 data_->num_prefix_chars_ - 1));
1236 // L >= log_mutex (callers must hold the log_mutex).
1237 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1242 // L >= log_mutex (callers must hold the log_mutex).
1243 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1244 if (data_->outvec_ != NULL) {
1245 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1246 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1247 // Omit prefix of message and trailing newline when recording in outvec_.
1248 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1249 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1250 data_->outvec_->push_back(string(start, len));
1256 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1257 if (data_->message_ != NULL) {
1258 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1259 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1260 // Omit prefix of message and trailing newline when writing to message_.
1261 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1262 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1263 data_->message_->assign(start, len);
1268 // L >= log_mutex (callers must hold the log_mutex).
1269 void LogMessage::SendToSyslogAndLog() {
1270 #ifdef HAVE_SYSLOG_H
1271 // Before any calls to syslog(), make a single call to openlog()
1272 static bool openlog_already_called = false;
1273 if (!openlog_already_called) {
1274 openlog(ProgramInvocationShortName(), LOG_CONS | LOG_NDELAY | LOG_PID,
1276 openlog_already_called = true;
1279 // This array maps Google severity levels to syslog levels
1280 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1281 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1282 int(data_->num_chars_to_syslog_),
1283 data_->message_text_ + data_->num_prefix_chars_);
1286 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1290 base::Logger* base::GetLogger(LogSeverity severity) {
1291 MutexLock l(&log_mutex);
1292 return LogDestination::log_destination(severity)->logger_;
1295 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1296 MutexLock l(&log_mutex);
1297 LogDestination::log_destination(severity)->logger_ = logger;
1300 // L < log_mutex. Acquires and releases mutex_.
1301 int64 LogMessage::num_messages(int severity) {
1302 MutexLock l(&log_mutex);
1303 return num_messages_[severity];
1306 // Output the COUNTER value. This is only valid if ostream is a
1308 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1309 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1310 CHECK(log == log->self());
1315 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1316 LogSeverity severity, int ctr,
1317 void (LogMessage::*send_method)())
1318 : LogMessage(file, line, severity, ctr, send_method) {
1321 ErrnoLogMessage::~ErrnoLogMessage() {
1322 // Don't access errno directly because it may have been altered
1323 // while streaming the message.
1325 posix_strerror_r(preserved_errno(), buf, sizeof(buf));
1326 stream() << ": " << buf << " [" << preserved_errno() << "]";
1329 void FlushLogFiles(LogSeverity min_severity) {
1330 LogDestination::FlushLogFiles(min_severity);
1333 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1334 LogDestination::FlushLogFilesUnsafe(min_severity);
1337 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1338 LogDestination::SetLogDestination(severity, base_filename);
1341 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1342 LogDestination::SetLogSymlink(severity, symlink_basename);
1345 LogSink::~LogSink() {
1348 void LogSink::WaitTillSent() {
1352 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1353 const struct ::tm* tm_time,
1354 const char* message, size_t message_len) {
1355 ostringstream stream(string(message, message_len));
1358 // FIXME(jrvb): Updating this to use the correct value for usecs
1359 // requires changing the signature for both this method and
1360 // LogSink::send(). This change needs to be done in a separate CL
1361 // so subclasses of LogSink can be updated at the same time.
1364 stream << LogSeverityNames[severity][0]
1365 << setw(2) << 1+tm_time->tm_mon
1366 << setw(2) << tm_time->tm_mday
1368 << setw(2) << tm_time->tm_hour << ':'
1369 << setw(2) << tm_time->tm_min << ':'
1370 << setw(2) << tm_time->tm_sec << '.'
1373 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1375 << file << ':' << line << "] ";
1377 stream << string(message, message_len);
1378 return stream.str();
1381 void AddLogSink(LogSink *destination) {
1382 LogDestination::AddLogSink(destination);
1385 void RemoveLogSink(LogSink *destination) {
1386 LogDestination::RemoveLogSink(destination);
1389 void SetLogFilenameExtension(const char* ext) {
1390 LogDestination::SetLogFilenameExtension(ext);
1393 void SetStderrLogging(LogSeverity min_severity) {
1394 LogDestination::SetStderrLogging(min_severity);
1397 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1398 LogDestination::SetEmailLogging(min_severity, addresses);
1401 void LogToStderr() {
1402 LogDestination::LogToStderr();
1406 namespace internal {
1408 bool GetExitOnDFatal() {
1409 MutexLock l(&log_mutex);
1410 return exit_on_dfatal;
1413 // Determines whether we exit the program for a LOG(DFATAL) message in
1414 // debug mode. It does this by skipping the call to Fail/FailQuietly.
1415 // This is intended for testing only.
1417 // This can have some effects on LOG(FATAL) as well. Failure messages
1418 // are always allocated (rather than sharing a buffer), the crash
1419 // reason is not recorded, the "gwq" status message is not updated,
1420 // and the stack trace is not recorded. The LOG(FATAL) *will* still
1421 // exit the program. Since this function is used only in testing,
1422 // these differences are acceptable.
1423 void SetExitOnDFatal(bool value) {
1424 MutexLock l(&log_mutex);
1425 exit_on_dfatal = value;
1428 } // namespace internal
1431 // use_logging controls whether the logging functions LOG/VLOG are used
1432 // to log errors. It should be set to false when the caller holds the
1434 static bool SendEmailInternal(const char*dest, const char *subject,
1435 const char*body, bool use_logging) {
1436 if (dest && *dest) {
1437 if ( use_logging ) {
1438 VLOG(1) << "Trying to send TITLE:" << subject
1439 << " BODY:" << body << " to " << dest;
1441 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1442 subject, body, dest);
1446 FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1447 FILE* pipe = popen(cmd.c_str(), "w");
1449 // Add the body if we have one
1451 fwrite(body, sizeof(char), strlen(body), pipe);
1452 bool ok = pclose(pipe) != -1;
1454 if ( use_logging ) {
1456 posix_strerror_r(errno, buf, sizeof(buf));
1457 LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf;
1460 posix_strerror_r(errno, buf, sizeof(buf));
1461 fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf);
1466 if ( use_logging ) {
1467 LOG(ERROR) << "Unable to send mail to " << dest;
1469 fprintf(stderr, "Unable to send mail to %s\n", dest);
1476 bool SendEmail(const char*dest, const char *subject, const char*body){
1477 return SendEmailInternal(dest, subject, body, true);
1480 static void GetTempDirectories(vector<string>* list) {
1483 // On windows we'll try to find a directory in this order:
1484 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1487 // C:/WINDOWS/ or C:/WINNT/
1490 if (GetTempPathA(MAX_PATH, tmp))
1491 list->push_back(tmp);
1492 list->push_back("C:\\tmp\\");
1493 list->push_back("C:\\temp\\");
1495 // Directories, in order of preference. If we find a dir that
1496 // exists, we stop adding other less-preferred dirs
1497 const char * candidates[] = {
1498 // Non-null only during unittest/regtest
1499 getenv("TEST_TMPDIR"),
1501 // Explicitly-supplied temp dirs
1502 getenv("TMPDIR"), getenv("TMP"),
1504 // If all else fails
1508 for (int i = 0; i < ARRAYSIZE(candidates); i++) {
1509 const char *d = candidates[i];
1510 if (!d) continue; // Empty env var
1512 // Make sure we don't surprise anyone who's expecting a '/'
1514 if (dstr[dstr.size() - 1] != '/') {
1517 list->push_back(dstr);
1519 struct stat statbuf;
1520 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1521 // We found a dir that exists - we're done.
1529 static vector<string>* logging_directories_list;
1531 const vector<string>& GetLoggingDirectories() {
1532 // Not strictly thread-safe but we're called early in InitGoogle().
1533 if (logging_directories_list == NULL) {
1534 logging_directories_list = new vector<string>;
1536 if ( !FLAGS_log_dir.empty() ) {
1537 // A dir was specified, we should use it
1538 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1540 GetTempDirectories(logging_directories_list);
1543 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1544 logging_directories_list->push_back(tmp);
1545 logging_directories_list->push_back(".\\");
1547 logging_directories_list->push_back("./");
1551 return *logging_directories_list;
1554 void TestOnly_ClearLoggingDirectoriesList() {
1555 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1556 "called from test code.\n");
1557 delete logging_directories_list;
1558 logging_directories_list = NULL;
1561 void GetExistingTempDirectories(vector<string>* list) {
1562 GetTempDirectories(list);
1563 vector<string>::iterator i_dir = list->begin();
1564 while( i_dir != list->end() ) {
1565 // zero arg to access means test for existence; no constant
1566 // defined on windows
1567 if ( access(i_dir->c_str(), 0) ) {
1568 i_dir = list->erase(i_dir);
1575 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1576 #ifdef HAVE_UNISTD_H
1577 struct stat statbuf;
1578 const int kCopyBlockSize = 8 << 10;
1579 char copybuf[kCopyBlockSize];
1580 int64 read_offset, write_offset;
1581 // Don't follow symlinks unless they're our own fd symlinks in /proc
1583 const char *procfd_prefix = "/proc/self/fd/";
1584 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1586 int fd = open(path, flags);
1588 if (errno == EFBIG) {
1589 // The log file in question has got too big for us to open. The
1590 // real fix for this would be to compile logging.cc (or probably
1591 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1593 // Instead just truncate the file to something we can manage
1594 if (truncate(path, 0) == -1) {
1595 PLOG(ERROR) << "Unable to truncate " << path;
1597 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1600 PLOG(ERROR) << "Unable to open " << path;
1605 if (fstat(fd, &statbuf) == -1) {
1606 PLOG(ERROR) << "Unable to fstat()";
1610 // See if the path refers to a regular file bigger than the
1612 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1613 if (statbuf.st_size <= limit) goto out_close_fd;
1614 if (statbuf.st_size <= keep) goto out_close_fd;
1616 // This log file is too large - we need to truncate it
1617 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1619 // Copy the last "keep" bytes of the file to the beginning of the file
1620 read_offset = statbuf.st_size - keep;
1622 int bytesin, bytesout;
1623 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1624 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1625 if (bytesout == -1) {
1626 PLOG(ERROR) << "Unable to write to " << path;
1628 } else if (bytesout != bytesin) {
1629 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1631 read_offset += bytesin;
1632 write_offset += bytesout;
1634 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1636 // Truncate the remainder of the file. If someone else writes to the
1637 // end of the file after our last read() above, we lose their latest
1638 // data. Too bad ...
1639 if (ftruncate(fd, write_offset) == -1) {
1640 PLOG(ERROR) << "Unable to truncate " << path;
1646 LOG(ERROR) << "No log truncation support.";
1650 void TruncateStdoutStderr() {
1651 #ifdef HAVE_UNISTD_H
1652 int64 limit = MaxLogSize() << 20;
1653 int64 keep = 1 << 20;
1654 TruncateLogFile("/proc/self/fd/1", limit, keep);
1655 TruncateLogFile("/proc/self/fd/2", limit, keep);
1657 LOG(ERROR) << "No log truncation support.";
1662 // Helper functions for string comparisons.
1663 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1664 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1665 const char* names) { \
1666 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1667 if (equal == expected) return NULL; \
1672 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1673 return new string(ss.str(), ss.pcount()); \
1676 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1677 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1678 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1679 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1680 #undef DEFINE_CHECK_STROP_IMPL
1682 int posix_strerror_r(int err, char *buf, size_t len) {
1683 // Sanity check input parameters
1684 if (buf == NULL || len <= 0) {
1689 // Reset buf and errno, and try calling whatever version of strerror_r()
1690 // is implemented by glibc
1692 int old_errno = errno;
1694 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1696 // Both versions set errno on failure
1698 // Should already be there, but better safe than sorry
1704 // POSIX is vague about whether the string will be terminated, although
1705 // is indirectly implies that typically ERANGE will be returned, instead
1706 // of truncating the string. This is different from the GNU implementation.
1707 // We play it safe by always terminating the string explicitly.
1708 buf[len-1] = '\000';
1710 // If the function succeeded, we can use its exit code to determine the
1711 // semantics implemented by glibc
1715 // GNU semantics detected
1720 #if defined(OS_MACOSX) || defined(OS_FREEBSD)
1721 if (reinterpret_cast<int>(rc) < sys_nerr) {
1722 // This means an error on MacOSX or FreeBSD.
1726 strncat(buf, rc, len-1);
1732 LogMessageFatal::LogMessageFatal(const char* file, int line) :
1733 LogMessage(file, line, FATAL) {}
1735 LogMessageFatal::LogMessageFatal(const char* file, int line,
1736 const CheckOpString& result) :
1737 LogMessage(file, line, result) {}
1739 LogMessageFatal::~LogMessageFatal() {
1744 _END_GOOGLE_NAMESPACE_