1 // Copyright (c) 1999, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite()
32 #include "utilities.h"
38 # include <unistd.h> // For _exit.
41 #include <sys/types.h>
43 #ifdef HAVE_SYS_UTSNAME_H
44 # include <sys/utsname.h> // For uname.
58 #include <errno.h> // for errno
60 #include "base/commandlineflags.h" // to get the program name
61 #include "glog/logging.h"
62 #include "glog/raw_logging.h"
63 #include "base/googleinit.h"
65 #ifdef HAVE_STACKTRACE
66 # include "stacktrace.h"
77 using std::ostringstream;
90 // There is no thread annotation support.
91 #define EXCLUSIVE_LOCKS_REQUIRED(mu)
93 static bool BoolFromEnv(const char *varname, bool defval) {
94 const char* const valstr = getenv(varname);
98 return memchr("tTyY1\0", valstr[0], 6) != NULL;
101 GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
102 "log messages go to stderr instead of logfiles");
103 GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
104 "log messages go to stderr in addition to logfiles");
106 GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
107 "Logs can grow very quickly and they are rarely read before they "
108 "need to be evicted from memory. Instead, drop them from memory "
109 "as soon as they are flushed to disk.");
110 _START_GOOGLE_NAMESPACE_
112 static const int64 kPageSize = getpagesize();
114 _END_GOOGLE_NAMESPACE_
117 // By default, errors (including fatal errors) get logged to stderr as
120 // The default is ERROR instead of FATAL so that users can see problems
121 // when they run a program without having to look in another file.
122 DEFINE_int32(stderrthreshold,
123 GOOGLE_NAMESPACE::GLOG_ERROR,
124 "log messages at or above this level are copied to stderr in "
125 "addition to logfiles. This flag obsoletes --alsologtostderr.");
127 GLOG_DEFINE_string(alsologtoemail, "",
128 "log messages go to these email addresses "
129 "in addition to logfiles");
130 GLOG_DEFINE_bool(log_prefix, true,
131 "Prepend the log prefix to the start of each log line");
132 GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
133 "actually get logged anywhere");
134 GLOG_DEFINE_int32(logbuflevel, 0,
135 "Buffer log messages logged at this level or lower"
136 " (-1 means don't buffer; 0 means buffer INFO only;"
138 GLOG_DEFINE_int32(logbufsecs, 30,
139 "Buffer log messages for at most this many seconds");
140 GLOG_DEFINE_int32(logemaillevel, 999,
141 "Email log messages logged at this level or higher"
142 " (0 means email all; 3 means email FATAL only;"
144 GLOG_DEFINE_string(logmailer, "/bin/mail",
145 "Mailer used to send logging email");
147 // Compute the default value for --log_dir
148 static const char* DefaultLogDir() {
150 env = getenv("GOOGLE_LOG_DIR");
151 if (env != NULL && env[0] != '\0') {
154 env = getenv("TEST_TMPDIR");
155 if (env != NULL && env[0] != '\0') {
161 GLOG_DEFINE_string(log_dir, DefaultLogDir(),
162 "If specified, logfiles are written into this directory instead "
163 "of the default logging directory.");
164 GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
165 "files in this directory");
167 GLOG_DEFINE_int32(max_log_size, 1800,
168 "approx. maximum log file size (in MB). A value of 0 will "
169 "be silently overridden to 1.");
171 GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
172 "Stop attempting to log to disk if the disk is full.");
174 GLOG_DEFINE_string(log_backtrace_at, "",
175 "Emit a backtrace when logging at file:linenum.");
177 // TODO(hamaji): consider windows
178 #define PATH_SEPARATOR '/'
180 static void GetHostName(string* hostname) {
181 #if defined(HAVE_SYS_UTSNAME_H)
183 if (0 != uname(&buf)) {
184 // ensure null termination on failure
185 *buf.nodename = '\0';
187 *hostname = buf.nodename;
188 #elif defined(OS_WINDOWS)
189 char buf[MAX_COMPUTERNAME_LENGTH + 1];
190 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
191 if (GetComputerNameA(buf, &len)) {
197 # warning There is no way to retrieve the host name.
198 *hostname = "(unknown)";
202 _START_GOOGLE_NAMESPACE_
204 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
205 static int32 MaxLogSize() {
206 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
209 // A mutex that allows only one thread to log at a time, to keep things from
210 // getting jumbled. Some other very uncommon logging operations (like
211 // changing the destination file for log messages of a given severity) also
212 // lock this mutex. Please be sure that anybody who might possibly need to
214 static Mutex log_mutex;
216 // Number of messages sent at each severity. Under log_mutex.
217 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
219 // Globally disable log writing (if disk is full)
220 static bool stop_writing = false;
222 const char*const LogSeverityNames[NUM_SEVERITIES] = {
223 "INFO", "WARNING", "ERROR", "FATAL"
226 // Has the user called SetExitOnDFatal(true)?
227 static bool exit_on_dfatal = true;
229 const char* GetLogSeverityName(LogSeverity severity) {
230 return LogSeverityNames[severity];
233 static bool SendEmailInternal(const char*dest, const char *subject,
234 const char*body, bool use_logging);
236 base::Logger::~Logger() {
241 // Encapsulates all file-system related state
242 class LogFileObject : public base::Logger {
244 LogFileObject(LogSeverity severity, const char* base_filename);
247 virtual void Write(bool force_flush, // Should we force a flush here?
248 time_t timestamp, // Timestamp for this entry
252 // Configuration options
253 void SetBasename(const char* basename);
254 void SetExtension(const char* ext);
255 void SetSymlinkBasename(const char* symlink_basename);
257 // Normal flushing routine
258 virtual void Flush();
260 // It is the actual file length for the system loggers,
261 // i.e., INFO, ERROR, etc.
262 virtual uint32 LogSize() {
267 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
268 // can avoid grabbing a lock. Usually Flush() calls it after
270 void FlushUnlocked();
273 static const uint32 kRolloverAttemptFrequency = 0x20;
276 bool base_filename_selected_;
277 string base_filename_;
278 string symlink_basename_;
279 string filename_extension_; // option users can specify (eg to add port#)
281 LogSeverity severity_;
282 uint32 bytes_since_flush_;
284 unsigned int rollover_attempt_;
285 int64 next_flush_time_; // cycle count at which to flush log
287 // Actually create a logfile using the value of base_filename_ and the
288 // supplied argument time_pid_string
289 // REQUIRES: lock_ is held
290 bool CreateLogfile(const string& time_pid_string);
295 class LogDestination {
297 friend class LogMessage;
298 friend void ReprintFatalMessage();
299 friend base::Logger* base::GetLogger(LogSeverity);
300 friend void base::SetLogger(LogSeverity, base::Logger*);
302 // These methods are just forwarded to by their global versions.
303 static void SetLogDestination(LogSeverity severity,
304 const char* base_filename);
305 static void SetLogSymlink(LogSeverity severity,
306 const char* symlink_basename);
307 static void AddLogSink(LogSink *destination);
308 static void RemoveLogSink(LogSink *destination);
309 static void SetLogFilenameExtension(const char* filename_extension);
310 static void SetStderrLogging(LogSeverity min_severity);
311 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
312 static void LogToStderr();
313 // Flush all log files that are at least at the given severity level
314 static void FlushLogFiles(int min_severity);
315 static void FlushLogFilesUnsafe(int min_severity);
317 // we set the maximum size of our packet to be 1400, the logic being
318 // to prevent fragmentation.
319 // Really this number is arbitrary.
320 static const int kNetworkBytes = 1400;
322 static const string& hostname();
324 static void DeleteLogDestinations();
327 LogDestination(LogSeverity severity, const char* base_filename);
328 ~LogDestination() { }
330 // Take a log message of a particular severity and log it to stderr
331 // iff it's of a high enough severity to deserve it.
332 static void MaybeLogToStderr(LogSeverity severity, const char* message,
335 // Take a log message of a particular severity and log it to email
336 // iff it's of a high enough severity to deserve it.
337 static void MaybeLogToEmail(LogSeverity severity, const char* message,
339 // Take a log message of a particular severity and log it to a file
340 // iff the base filename is not "" (which means "don't log to me")
341 static void MaybeLogToLogfile(LogSeverity severity,
343 const char* message, size_t len);
344 // Take a log message of a particular severity and log it to the file
345 // for that severity and also for all files with severity less than
347 static void LogToAllLogfiles(LogSeverity severity,
349 const char* message, size_t len);
351 // Send logging info to all registered sinks.
352 static void LogToSinks(LogSeverity severity,
353 const char *full_filename,
354 const char *base_filename,
356 const struct ::tm* tm_time,
360 // Wait for all registered sinks via WaitTillSent
361 // including the optional one in "data".
362 static void WaitForSinks(LogMessage::LogMessageData* data);
364 static LogDestination* log_destination(LogSeverity severity);
366 LogFileObject fileobject_;
367 base::Logger* logger_; // Either &fileobject_, or wrapper around it
369 static LogDestination* log_destinations_[NUM_SEVERITIES];
370 static LogSeverity email_logging_severity_;
371 static string addresses_;
372 static string hostname_;
374 // arbitrary global logging destinations.
375 static vector<LogSink*>* sinks_;
377 // Protects the vector sinks_,
378 // but not the LogSink objects its elements reference.
379 static Mutex sink_mutex_;
382 LogDestination(const LogDestination&);
383 LogDestination& operator=(const LogDestination&);
386 // Errors do not get logged to email by default.
387 LogSeverity LogDestination::email_logging_severity_ = 99999;
389 string LogDestination::addresses_;
390 string LogDestination::hostname_;
392 vector<LogSink*>* LogDestination::sinks_ = NULL;
393 Mutex LogDestination::sink_mutex_;
396 const string& LogDestination::hostname() {
397 if (hostname_.empty()) {
398 GetHostName(&hostname_);
399 if (hostname_.empty()) {
400 hostname_ = "(unknown)";
406 LogDestination::LogDestination(LogSeverity severity,
407 const char* base_filename)
408 : fileobject_(severity, base_filename),
409 logger_(&fileobject_) {
412 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
413 // assume we have the log_mutex or we simply don't care
415 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
416 LogDestination* log = log_destination(i);
418 // Flush the base fileobject_ logger directly instead of going
419 // through any wrappers to reduce chance of deadlock.
420 log->fileobject_.FlushUnlocked();
425 inline void LogDestination::FlushLogFiles(int min_severity) {
426 // Prevent any subtle race conditions by wrapping a mutex lock around
428 MutexLock l(&log_mutex);
429 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
430 LogDestination* log = log_destination(i);
432 log->logger_->Flush();
437 inline void LogDestination::SetLogDestination(LogSeverity severity,
438 const char* base_filename) {
439 assert(severity >= 0 && severity < NUM_SEVERITIES);
440 // Prevent any subtle race conditions by wrapping a mutex lock around
442 MutexLock l(&log_mutex);
443 log_destination(severity)->fileobject_.SetBasename(base_filename);
446 inline void LogDestination::SetLogSymlink(LogSeverity severity,
447 const char* symlink_basename) {
448 CHECK_GE(severity, 0);
449 CHECK_LT(severity, NUM_SEVERITIES);
450 MutexLock l(&log_mutex);
451 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
454 inline void LogDestination::AddLogSink(LogSink *destination) {
455 // Prevent any subtle race conditions by wrapping a mutex lock around
457 MutexLock l(&sink_mutex_);
458 if (!sinks_) sinks_ = new vector<LogSink*>;
459 sinks_->push_back(destination);
462 inline void LogDestination::RemoveLogSink(LogSink *destination) {
463 // Prevent any subtle race conditions by wrapping a mutex lock around
465 MutexLock l(&sink_mutex_);
466 // This doesn't keep the sinks in order, but who cares?
468 for (int i = sinks_->size() - 1; i >= 0; i--) {
469 if ((*sinks_)[i] == destination) {
470 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
478 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
479 // Prevent any subtle race conditions by wrapping a mutex lock around
481 MutexLock l(&log_mutex);
482 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
483 log_destination(severity)->fileobject_.SetExtension(ext);
487 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
488 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
489 // Prevent any subtle race conditions by wrapping a mutex lock around
491 MutexLock l(&log_mutex);
492 FLAGS_stderrthreshold = min_severity;
495 inline void LogDestination::LogToStderr() {
496 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
497 // SetLogDestination already do the locking!
498 SetStderrLogging(0); // thus everything is "also" logged to stderr
499 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
500 SetLogDestination(i, ""); // "" turns off logging to a logfile
504 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
505 const char* addresses) {
506 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
507 // Prevent any subtle race conditions by wrapping a mutex lock around
509 MutexLock l(&log_mutex);
510 LogDestination::email_logging_severity_ = min_severity;
511 LogDestination::addresses_ = addresses;
514 static void WriteToStderr(const char* message, size_t len) {
515 // Avoid using cerr from this module since we may get called during
516 // exit code, and cerr may be partially or fully destroyed by then.
517 fwrite(message, len, 1, stderr);
520 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
521 const char* message, size_t len) {
522 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
523 WriteToStderr(message, len);
525 // On Windows, also output to the debugger
526 ::OutputDebugStringA(string(message,len).c_str());
532 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
533 const char* message, size_t len) {
534 if (severity >= email_logging_severity_ ||
535 severity >= FLAGS_logemaillevel) {
536 string to(FLAGS_alsologtoemail);
537 if (!addresses_.empty()) {
543 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
544 glog_internal_namespace_::ProgramInvocationShortName());
545 string body(hostname());
547 body.append(message, len);
549 // should NOT use SendEmail(). The caller of this function holds the
550 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
551 // acquire the log_mutex object. Use SendEmailInternal() and set
552 // use_logging to false.
553 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
558 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
562 const bool should_flush = severity > FLAGS_logbuflevel;
563 LogDestination* destination = log_destination(severity);
564 destination->logger_->Write(should_flush, timestamp, message, len);
567 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
572 if ( FLAGS_logtostderr ) // global flag: never log to file
573 WriteToStderr(message, len);
575 for (int i = severity; i >= 0; --i)
576 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
580 inline void LogDestination::LogToSinks(LogSeverity severity,
581 const char *full_filename,
582 const char *base_filename,
584 const struct ::tm* tm_time,
586 size_t message_len) {
587 ReaderMutexLock l(&sink_mutex_);
589 for (int i = sinks_->size() - 1; i >= 0; i--) {
590 (*sinks_)[i]->send(severity, full_filename, base_filename,
591 line, tm_time, message, message_len);
596 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
597 ReaderMutexLock l(&sink_mutex_);
599 for (int i = sinks_->size() - 1; i >= 0; i--) {
600 (*sinks_)[i]->WaitTillSent();
603 const bool send_to_sink =
604 (data->send_method_ == &LogMessage::SendToSink) ||
605 (data->send_method_ == &LogMessage::SendToSinkAndLog);
606 if (send_to_sink && data->sink_ != NULL) {
607 data->sink_->WaitTillSent();
611 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
613 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
614 assert(severity >=0 && severity < NUM_SEVERITIES);
615 if (!log_destinations_[severity]) {
616 log_destinations_[severity] = new LogDestination(severity, NULL);
618 return log_destinations_[severity];
621 void LogDestination::DeleteLogDestinations() {
622 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
623 delete log_destinations_[severity];
624 log_destinations_[severity] = NULL;
630 LogFileObject::LogFileObject(LogSeverity severity,
631 const char* base_filename)
632 : base_filename_selected_(base_filename != NULL),
633 base_filename_((base_filename != NULL) ? base_filename : ""),
634 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
635 filename_extension_(),
638 bytes_since_flush_(0),
640 rollover_attempt_(kRolloverAttemptFrequency-1),
641 next_flush_time_(0) {
642 assert(severity >= 0);
643 assert(severity < NUM_SEVERITIES);
646 LogFileObject::~LogFileObject() {
654 void LogFileObject::SetBasename(const char* basename) {
656 base_filename_selected_ = true;
657 if (base_filename_ != basename) {
658 // Get rid of old log file since we are changing names
662 rollover_attempt_ = kRolloverAttemptFrequency-1;
664 base_filename_ = basename;
668 void LogFileObject::SetExtension(const char* ext) {
670 if (filename_extension_ != ext) {
671 // Get rid of old log file since we are changing names
675 rollover_attempt_ = kRolloverAttemptFrequency-1;
677 filename_extension_ = ext;
681 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
683 symlink_basename_ = symlink_basename;
686 void LogFileObject::Flush() {
691 void LogFileObject::FlushUnlocked(){
694 bytes_since_flush_ = 0;
696 // Figure out when we are due for another flush.
697 const int64 next = (FLAGS_logbufsecs
698 * static_cast<int64>(1000000)); // in usec
699 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
702 bool LogFileObject::CreateLogfile(const string& time_pid_string) {
703 string string_filename = base_filename_+filename_extension_+
705 const char* filename = string_filename.c_str();
706 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
707 if (fd == -1) return false;
709 // Mark the file close-on-exec. We don't really care if this fails
710 fcntl(fd, F_SETFD, FD_CLOEXEC);
713 file_ = fdopen(fd, "a"); // Make a FILE*.
714 if (file_ == NULL) { // Man, we're screwed!
716 unlink(filename); // Erase the half-baked evidence: an unusable log file
720 // We try to create a symlink called <program_name>.<severity>,
721 // which is easier to use. (Every time we create a new logfile,
722 // we destroy the old symlink and create a new one, so it always
723 // points to the latest logfile.) If it fails, we're sad but it's
725 if (!symlink_basename_.empty()) {
726 // take directory from filename
727 const char* slash = strrchr(filename, PATH_SEPARATOR);
728 const string linkname =
729 symlink_basename_ + '.' + LogSeverityNames[severity_];
731 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
732 linkpath += linkname;
733 unlink(linkpath.c_str()); // delete old one if it exists
735 // We must have unistd.h.
737 // Make the symlink be relative (in the same dir) so that if the
738 // entire log directory gets relocated the link is still valid.
739 const char *linkdest = slash ? (slash + 1) : filename;
740 if (symlink(linkdest, linkpath.c_str()) != 0) {
741 // silently ignore failures
744 // Make an additional link to the log file in a place specified by
745 // FLAGS_log_link, if indicated
746 if (!FLAGS_log_link.empty()) {
747 linkpath = FLAGS_log_link + "/" + linkname;
748 unlink(linkpath.c_str()); // delete old one if it exists
749 if (symlink(filename, linkpath.c_str()) != 0) {
750 // silently ignore failures
756 return true; // Everything worked
759 void LogFileObject::Write(bool force_flush,
765 // We don't log if the base_name_ is "" (which means "don't write")
766 if (base_filename_selected_ && base_filename_.empty()) {
770 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
772 if (file_ != NULL) fclose(file_);
774 file_length_ = bytes_since_flush_ = 0;
775 rollover_attempt_ = kRolloverAttemptFrequency-1;
778 // If there's no destination file, make one before outputting
780 // Try to rollover the log file every 32 log messages. The only time
781 // this could matter would be when we have trouble creating the log
782 // file. If that happens, we'll lose lots of log messages, of course!
783 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
784 rollover_attempt_ = 0;
787 localtime_r(×tamp, &tm_time);
789 // The logfile's filename will have the date/time & pid in it
790 ostringstream time_pid_stream;
791 time_pid_stream.fill('0');
792 time_pid_stream << 1900+tm_time.tm_year
793 << setw(2) << 1+tm_time.tm_mon
794 << setw(2) << tm_time.tm_mday
796 << setw(2) << tm_time.tm_hour
797 << setw(2) << tm_time.tm_min
798 << setw(2) << tm_time.tm_sec
800 << GetMainThreadPid();
801 const string& time_pid_string = time_pid_stream.str();
803 if (base_filename_selected_) {
804 if (!CreateLogfile(time_pid_string)) {
805 perror("Could not create log file");
806 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
807 time_pid_string.c_str());
811 // If no base filename for logs of this severity has been set, use a
812 // default base filename of
813 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
814 // logfiles will have names like
815 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
816 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
817 // and 4354 is the pid of the logging process. The date & time reflect
818 // when the file was created for output.
820 // Where does the file get put? Successively try the directories
822 string stripped_filename(
823 glog_internal_namespace_::ProgramInvocationShortName());
825 GetHostName(&hostname);
827 string uidname = MyUserName();
828 // We should not call CHECK() here because this function can be
829 // called after holding on to log_mutex. We don't want to
830 // attempt to hold on to the same mutex, and get into a
831 // deadlock. Simply use a name like invalid-user.
832 if (uidname.empty()) uidname = "invalid-user";
834 stripped_filename = stripped_filename+'.'+hostname+'.'
836 +LogSeverityNames[severity_]+'.';
837 // We're going to (potentially) try to put logs in several different dirs
838 const vector<string> & log_dirs = GetLoggingDirectories();
840 // Go through the list of dirs, and try to create the log file in each
841 // until we succeed or run out of options
842 bool success = false;
843 for (vector<string>::const_iterator dir = log_dirs.begin();
844 dir != log_dirs.end();
846 base_filename_ = *dir + "/" + stripped_filename;
847 if ( CreateLogfile(time_pid_string) ) {
852 // If we never succeeded, we have to give up
853 if ( success == false ) {
854 perror("Could not create logging file");
855 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
856 time_pid_string.c_str());
861 // Write a header message into the log file
862 ostringstream file_header_stream;
863 file_header_stream.fill('0');
864 file_header_stream << "Log file created at: "
865 << 1900+tm_time.tm_year << '/'
866 << setw(2) << 1+tm_time.tm_mon << '/'
867 << setw(2) << tm_time.tm_mday
869 << setw(2) << tm_time.tm_hour << ':'
870 << setw(2) << tm_time.tm_min << ':'
871 << setw(2) << tm_time.tm_sec << '\n'
872 << "Running on machine: "
873 << LogDestination::hostname() << '\n'
874 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
875 << "threadid file:line] msg" << '\n';
876 const string& file_header_string = file_header_stream.str();
878 const int header_len = file_header_string.size();
879 fwrite(file_header_string.data(), 1, header_len, file_);
880 file_length_ += header_len;
881 bytes_since_flush_ += header_len;
885 if ( !stop_writing ) {
886 // fwrite() doesn't return an error when the disk is full, for
887 // messages that are less than 4096 bytes. When the disk is full,
888 // it returns the message length for messages that are less than
889 // 4096 bytes. fwrite() returns 4096 for message lengths that are
890 // greater than 4096, thereby indicating an error.
892 fwrite(message, 1, message_len, file_);
893 if ( FLAGS_stop_logging_if_full_disk &&
894 errno == ENOSPC ) { // disk full, stop writing to disk
895 stop_writing = true; // until the disk is
898 file_length_ += message_len;
899 bytes_since_flush_ += message_len;
902 if ( CycleClock_Now() >= next_flush_time_ )
903 stop_writing = false; // check to see if disk has free space.
904 return; // no need to flush
907 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
908 // or every "FLAGS_logbufsecs" seconds.
910 (bytes_since_flush_ >= 1000000) ||
911 (CycleClock_Now() >= next_flush_time_) ) {
914 if (FLAGS_drop_log_memory) {
915 if (file_length_ >= logging::kPageSize) {
916 // don't evict the most recent page
917 uint32 len = file_length_ & ~(logging::kPageSize - 1);
918 posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
927 // An arbitrary limit on the length of a single log message. This
928 // is so that streaming can be done more efficiently.
929 const size_t LogMessage::kMaxLogMessageLen = 30000;
931 // Static log data space to avoid alloc failures in a LOG(FATAL)
933 // Since multiple threads may call LOG(FATAL), and we want to preserve
934 // the data from the first call, we allocate two sets of space. One
935 // for exclusive use by the first thread, and one for shared use by
936 // all other threads.
937 static Mutex fatal_msg_lock;
938 static CrashReason crash_reason;
939 static bool fatal_msg_exclusive = true;
940 static char fatal_msg_buf_exclusive[LogMessage::kMaxLogMessageLen+1];
941 static char fatal_msg_buf_shared[LogMessage::kMaxLogMessageLen+1];
942 static LogMessage::LogStream fatal_msg_stream_exclusive(
943 fatal_msg_buf_exclusive, LogMessage::kMaxLogMessageLen, 0);
944 static LogMessage::LogStream fatal_msg_stream_shared(
945 fatal_msg_buf_shared, LogMessage::kMaxLogMessageLen, 0);
946 LogMessage::LogMessageData LogMessage::fatal_msg_data_exclusive_;
947 LogMessage::LogMessageData LogMessage::fatal_msg_data_shared_;
949 LogMessage::LogMessageData::~LogMessageData() {
951 delete stream_alloc_;
954 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
955 int ctr, void (LogMessage::*send_method)()) {
956 Init(file, line, severity, send_method);
957 data_->stream_->set_ctr(ctr);
960 LogMessage::LogMessage(const char* file, int line,
961 const CheckOpString& result) {
962 Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
963 stream() << "Check failed: " << (*result.str_) << " ";
966 LogMessage::LogMessage(const char* file, int line) {
967 Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
970 LogMessage::LogMessage(const char* file, int line, LogSeverity severity) {
971 Init(file, line, severity, &LogMessage::SendToLog);
974 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
975 LogSink* sink, bool also_send_to_log) {
976 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
977 &LogMessage::SendToSink);
978 data_->sink_ = sink; // override Init()'s setting to NULL
981 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
982 vector<string> *outvec) {
983 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
984 data_->outvec_ = outvec; // override Init()'s setting to NULL
987 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
989 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
990 data_->message_ = message; // override Init()'s setting to NULL
993 void LogMessage::Init(const char* file,
995 LogSeverity severity,
996 void (LogMessage::*send_method)()) {
998 if (severity != GLOG_FATAL || !exit_on_dfatal) {
999 allocated_ = new LogMessageData();
1001 data_->buf_ = new char[kMaxLogMessageLen+1];
1002 data_->message_text_ = data_->buf_;
1003 data_->stream_alloc_ =
1004 new LogStream(data_->message_text_, kMaxLogMessageLen, 0);
1005 data_->stream_ = data_->stream_alloc_;
1006 data_->first_fatal_ = false;
1008 MutexLock l(&fatal_msg_lock);
1009 if (fatal_msg_exclusive) {
1010 fatal_msg_exclusive = false;
1011 data_ = &fatal_msg_data_exclusive_;
1012 data_->message_text_ = fatal_msg_buf_exclusive;
1013 data_->stream_ = &fatal_msg_stream_exclusive;
1014 data_->first_fatal_ = true;
1016 data_ = &fatal_msg_data_shared_;
1017 data_->message_text_ = fatal_msg_buf_shared;
1018 data_->stream_ = &fatal_msg_stream_shared;
1019 data_->first_fatal_ = false;
1021 data_->stream_alloc_ = NULL;
1025 data_->preserved_errno_ = errno;
1026 data_->severity_ = severity;
1027 data_->line_ = line;
1028 data_->send_method_ = send_method;
1029 data_->sink_ = NULL;
1030 data_->outvec_ = NULL;
1031 WallTime now = WallTime_Now();
1032 data_->timestamp_ = static_cast<time_t>(now);
1033 localtime_r(&data_->timestamp_, &data_->tm_time_);
1034 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1035 RawLog__SetLastTime(data_->tm_time_, usecs);
1037 data_->num_chars_to_log_ = 0;
1038 data_->num_chars_to_syslog_ = 0;
1039 data_->basename_ = const_basename(file);
1040 data_->fullname_ = file;
1041 data_->has_been_flushed_ = false;
1043 // If specified, prepend a prefix to each line. For example:
1044 // I1018 160715 f5d4fbb0 logging.cc:1153]
1045 // (log level, GMT month, date, time, thread_id, file basename, line)
1046 // We exclude the thread_id for the default thread.
1047 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1048 stream() << LogSeverityNames[severity][0]
1049 << setw(2) << 1+data_->tm_time_.tm_mon
1050 << setw(2) << data_->tm_time_.tm_mday
1052 << setw(2) << data_->tm_time_.tm_hour << ':'
1053 << setw(2) << data_->tm_time_.tm_min << ':'
1054 << setw(2) << data_->tm_time_.tm_sec << "."
1057 << setfill(' ') << setw(5)
1058 << static_cast<unsigned int>(GetTID()) << setfill('0')
1060 << data_->basename_ << ':' << data_->line_ << "] ";
1062 data_->num_prefix_chars_ = data_->stream_->pcount();
1064 if (!FLAGS_log_backtrace_at.empty()) {
1066 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1067 #ifdef HAVE_STACKTRACE
1068 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1070 DumpStackTraceToString(&stacktrace);
1071 stream() << " (stacktrace:\n" << stacktrace << ") ";
1077 LogMessage::~LogMessage() {
1082 // Flush buffered message, called by the destructor, or any other function
1083 // that needs to synchronize the log.
1084 void LogMessage::Flush() {
1085 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1088 data_->num_chars_to_log_ = data_->stream_->pcount();
1089 data_->num_chars_to_syslog_ =
1090 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1092 // Do we need to add a \n to the end of this message?
1093 bool append_newline =
1094 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1095 char original_final_char = '\0';
1097 // If we do need to add a \n, we'll do it by violating the memory of the
1098 // ostrstream buffer. This is quick, and we'll make sure to undo our
1099 // modification before anything else is done with the ostrstream. It
1100 // would be preferable not to do things this way, but it seems to be
1101 // the best way to deal with this.
1102 if (append_newline) {
1103 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1104 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1107 // Prevent any subtle race conditions by wrapping a mutex lock around
1108 // the actual logging action per se.
1110 MutexLock l(&log_mutex);
1111 (this->*(data_->send_method_))();
1112 ++num_messages_[static_cast<int>(data_->severity_)];
1114 LogDestination::WaitForSinks(data_);
1116 if (append_newline) {
1117 // Fix the ostrstream back how it was before we screwed with it.
1118 // It's 99.44% certain that we don't need to worry about doing this.
1119 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1122 // If errno was already set before we enter the logging call, we'll
1123 // set it back to that value when we return from the logging call.
1124 // It happens often that we log an error message after a syscall
1125 // failure, which can potentially set the errno to some other
1126 // values. We would like to preserve the original errno.
1127 if (data_->preserved_errno_ != 0) {
1128 errno = data_->preserved_errno_;
1131 // Note that this message is now safely logged. If we're asked to flush
1132 // again, as a result of destruction, say, we'll do nothing on future calls.
1133 data_->has_been_flushed_ = true;
1136 // Copy of first FATAL log message so that we can print it out again
1137 // after all the stack traces. To preserve legacy behavior, we don't
1138 // use fatal_msg_buf_exclusive.
1139 static time_t fatal_time;
1140 static char fatal_message[256];
1142 void ReprintFatalMessage() {
1143 if (fatal_message[0]) {
1144 const int n = strlen(fatal_message);
1145 if (!FLAGS_logtostderr) {
1146 // Also write to stderr
1147 WriteToStderr(fatal_message, n);
1149 LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1153 // L >= log_mutex (callers must hold the log_mutex).
1154 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1155 static bool already_warned_before_initgoogle = false;
1157 log_mutex.AssertHeld();
1159 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1160 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1162 // Messages of a given severity get logged to lower severity logs, too
1164 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1165 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1166 "written to STDERR\n";
1167 WriteToStderr(w, strlen(w));
1168 already_warned_before_initgoogle = true;
1171 // global flag: never log to file if set. Also -- don't log to a
1172 // file if we haven't parsed the command line flags to get the
1174 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1175 WriteToStderr(data_->message_text_, data_->num_chars_to_log_);
1177 // this could be protected by a flag if necessary.
1178 LogDestination::LogToSinks(data_->severity_,
1179 data_->fullname_, data_->basename_,
1180 data_->line_, &data_->tm_time_,
1181 data_->message_text_ + data_->num_prefix_chars_,
1182 (data_->num_chars_to_log_ -
1183 data_->num_prefix_chars_ - 1));
1186 // log this message to all log files of severity <= severity_
1187 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1188 data_->message_text_,
1189 data_->num_chars_to_log_);
1191 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1192 data_->num_chars_to_log_);
1193 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1194 data_->num_chars_to_log_);
1195 LogDestination::LogToSinks(data_->severity_,
1196 data_->fullname_, data_->basename_,
1197 data_->line_, &data_->tm_time_,
1198 data_->message_text_ + data_->num_prefix_chars_,
1199 (data_->num_chars_to_log_
1200 - data_->num_prefix_chars_ - 1));
1201 // NOTE: -1 removes trailing \n
1204 // If we log a FATAL message, flush all the log destinations, then toss
1205 // a signal for others to catch. We leave the logs in a state that
1206 // someone else can use them (as long as they flush afterwards)
1207 if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1208 if (data_->first_fatal_) {
1209 // Store crash information so that it is accessible from within signal
1210 // handlers that may be invoked later.
1211 RecordCrashReason(&crash_reason);
1212 SetCrashReason(&crash_reason);
1214 // Store shortened fatal message for other logs and GWQ status
1215 const int copy = min<int>(data_->num_chars_to_log_,
1216 sizeof(fatal_message)-1);
1217 memcpy(fatal_message, data_->message_text_, copy);
1218 fatal_message[copy] = '\0';
1219 fatal_time = data_->timestamp_;
1222 if (!FLAGS_logtostderr) {
1223 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1224 if ( LogDestination::log_destinations_[i] )
1225 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1229 // release the lock that our caller (directly or indirectly)
1230 // LogMessage::~LogMessage() grabbed so that signal handlers
1231 // can use the logging facility. Alternately, we could add
1232 // an entire unsafe logging interface to bypass locking
1233 // for signal handlers but this seems simpler.
1235 LogDestination::WaitForSinks(data_);
1237 const char* message = "*** Check failure stack trace: ***\n";
1238 if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1245 void LogMessage::RecordCrashReason(
1246 glog_internal_namespace_::CrashReason* reason) {
1247 reason->filename = fatal_msg_data_exclusive_.fullname_;
1248 reason->line_number = fatal_msg_data_exclusive_.line_;
1249 reason->message = fatal_msg_buf_exclusive +
1250 fatal_msg_data_exclusive_.num_prefix_chars_;
1251 #ifdef HAVE_STACKTRACE
1252 // Retrieve the stack trace, omitting the logging frames that got us here.
1253 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1259 #ifdef HAVE___ATTRIBUTE__
1260 # define ATTRIBUTE_NORETURN __attribute__((noreturn))
1262 # define ATTRIBUTE_NORETURN
1265 static void logging_fail() ATTRIBUTE_NORETURN;
1267 static void logging_fail() {
1268 #if defined(_DEBUG) && defined(_MSC_VER)
1269 // When debugging on windows, avoid the obnoxious dialog and make
1270 // it possible to continue past a LOG(FATAL) in the debugger
1277 typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN;
1279 GOOGLE_GLOG_DLL_DECL
1280 logging_fail_func_t g_logging_fail_func = &logging_fail;
1282 void InstallFailureFunction(void (*fail_func)()) {
1283 g_logging_fail_func = (logging_fail_func_t)fail_func;
1286 void LogMessage::Fail() {
1287 g_logging_fail_func();
1290 // L >= log_mutex (callers must hold the log_mutex).
1291 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1292 if (data_->sink_ != NULL) {
1293 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1294 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1295 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1296 data_->line_, &data_->tm_time_,
1297 data_->message_text_ + data_->num_prefix_chars_,
1298 (data_->num_chars_to_log_ -
1299 data_->num_prefix_chars_ - 1));
1303 // L >= log_mutex (callers must hold the log_mutex).
1304 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1309 // L >= log_mutex (callers must hold the log_mutex).
1310 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1311 if (data_->outvec_ != NULL) {
1312 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1313 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1314 // Omit prefix of message and trailing newline when recording in outvec_.
1315 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1316 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1317 data_->outvec_->push_back(string(start, len));
1323 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1324 if (data_->message_ != NULL) {
1325 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1326 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1327 // Omit prefix of message and trailing newline when writing to message_.
1328 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1329 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1330 data_->message_->assign(start, len);
1335 // L >= log_mutex (callers must hold the log_mutex).
1336 void LogMessage::SendToSyslogAndLog() {
1337 #ifdef HAVE_SYSLOG_H
1338 // Before any calls to syslog(), make a single call to openlog()
1339 static bool openlog_already_called = false;
1340 if (!openlog_already_called) {
1341 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1342 LOG_CONS | LOG_NDELAY | LOG_PID,
1344 openlog_already_called = true;
1347 // This array maps Google severity levels to syslog levels
1348 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1349 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1350 int(data_->num_chars_to_syslog_),
1351 data_->message_text_ + data_->num_prefix_chars_);
1354 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1358 base::Logger* base::GetLogger(LogSeverity severity) {
1359 MutexLock l(&log_mutex);
1360 return LogDestination::log_destination(severity)->logger_;
1363 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1364 MutexLock l(&log_mutex);
1365 LogDestination::log_destination(severity)->logger_ = logger;
1368 // L < log_mutex. Acquires and releases mutex_.
1369 int64 LogMessage::num_messages(int severity) {
1370 MutexLock l(&log_mutex);
1371 return num_messages_[severity];
1374 // Output the COUNTER value. This is only valid if ostream is a
1376 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1378 LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
1380 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1382 CHECK(log && log == log->self())
1383 << "You must not use COUNTER with non-glog ostream";
1388 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1389 LogSeverity severity, int ctr,
1390 void (LogMessage::*send_method)())
1391 : LogMessage(file, line, severity, ctr, send_method) {
1394 ErrnoLogMessage::~ErrnoLogMessage() {
1395 // Don't access errno directly because it may have been altered
1396 // while streaming the message.
1398 posix_strerror_r(preserved_errno(), buf, sizeof(buf));
1399 stream() << ": " << buf << " [" << preserved_errno() << "]";
1402 void FlushLogFiles(LogSeverity min_severity) {
1403 LogDestination::FlushLogFiles(min_severity);
1406 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1407 LogDestination::FlushLogFilesUnsafe(min_severity);
1410 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1411 LogDestination::SetLogDestination(severity, base_filename);
1414 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1415 LogDestination::SetLogSymlink(severity, symlink_basename);
1418 LogSink::~LogSink() {
1421 void LogSink::WaitTillSent() {
1425 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1426 const struct ::tm* tm_time,
1427 const char* message, size_t message_len) {
1428 ostringstream stream(string(message, message_len));
1431 // FIXME(jrvb): Updating this to use the correct value for usecs
1432 // requires changing the signature for both this method and
1433 // LogSink::send(). This change needs to be done in a separate CL
1434 // so subclasses of LogSink can be updated at the same time.
1437 stream << LogSeverityNames[severity][0]
1438 << setw(2) << 1+tm_time->tm_mon
1439 << setw(2) << tm_time->tm_mday
1441 << setw(2) << tm_time->tm_hour << ':'
1442 << setw(2) << tm_time->tm_min << ':'
1443 << setw(2) << tm_time->tm_sec << '.'
1446 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1448 << file << ':' << line << "] ";
1450 stream << string(message, message_len);
1451 return stream.str();
1454 void AddLogSink(LogSink *destination) {
1455 LogDestination::AddLogSink(destination);
1458 void RemoveLogSink(LogSink *destination) {
1459 LogDestination::RemoveLogSink(destination);
1462 void SetLogFilenameExtension(const char* ext) {
1463 LogDestination::SetLogFilenameExtension(ext);
1466 void SetStderrLogging(LogSeverity min_severity) {
1467 LogDestination::SetStderrLogging(min_severity);
1470 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1471 LogDestination::SetEmailLogging(min_severity, addresses);
1474 void LogToStderr() {
1475 LogDestination::LogToStderr();
1479 namespace internal {
1481 bool GetExitOnDFatal() {
1482 MutexLock l(&log_mutex);
1483 return exit_on_dfatal;
1486 // Determines whether we exit the program for a LOG(DFATAL) message in
1487 // debug mode. It does this by skipping the call to Fail/FailQuietly.
1488 // This is intended for testing only.
1490 // This can have some effects on LOG(FATAL) as well. Failure messages
1491 // are always allocated (rather than sharing a buffer), the crash
1492 // reason is not recorded, the "gwq" status message is not updated,
1493 // and the stack trace is not recorded. The LOG(FATAL) *will* still
1494 // exit the program. Since this function is used only in testing,
1495 // these differences are acceptable.
1496 void SetExitOnDFatal(bool value) {
1497 MutexLock l(&log_mutex);
1498 exit_on_dfatal = value;
1501 } // namespace internal
1504 // use_logging controls whether the logging functions LOG/VLOG are used
1505 // to log errors. It should be set to false when the caller holds the
1507 static bool SendEmailInternal(const char*dest, const char *subject,
1508 const char*body, bool use_logging) {
1509 if (dest && *dest) {
1510 if ( use_logging ) {
1511 VLOG(1) << "Trying to send TITLE:" << subject
1512 << " BODY:" << body << " to " << dest;
1514 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1515 subject, body, dest);
1519 FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1520 FILE* pipe = popen(cmd.c_str(), "w");
1522 // Add the body if we have one
1524 fwrite(body, sizeof(char), strlen(body), pipe);
1525 bool ok = pclose(pipe) != -1;
1527 if ( use_logging ) {
1529 posix_strerror_r(errno, buf, sizeof(buf));
1530 LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf;
1533 posix_strerror_r(errno, buf, sizeof(buf));
1534 fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf);
1539 if ( use_logging ) {
1540 LOG(ERROR) << "Unable to send mail to " << dest;
1542 fprintf(stderr, "Unable to send mail to %s\n", dest);
1549 bool SendEmail(const char*dest, const char *subject, const char*body){
1550 return SendEmailInternal(dest, subject, body, true);
1553 static void GetTempDirectories(vector<string>* list) {
1556 // On windows we'll try to find a directory in this order:
1557 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1560 // C:/WINDOWS/ or C:/WINNT/
1563 if (GetTempPathA(MAX_PATH, tmp))
1564 list->push_back(tmp);
1565 list->push_back("C:\\tmp\\");
1566 list->push_back("C:\\temp\\");
1568 // Directories, in order of preference. If we find a dir that
1569 // exists, we stop adding other less-preferred dirs
1570 const char * candidates[] = {
1571 // Non-null only during unittest/regtest
1572 getenv("TEST_TMPDIR"),
1574 // Explicitly-supplied temp dirs
1575 getenv("TMPDIR"), getenv("TMP"),
1577 // If all else fails
1581 for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
1582 const char *d = candidates[i];
1583 if (!d) continue; // Empty env var
1585 // Make sure we don't surprise anyone who's expecting a '/'
1587 if (dstr[dstr.size() - 1] != '/') {
1590 list->push_back(dstr);
1592 struct stat statbuf;
1593 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1594 // We found a dir that exists - we're done.
1602 static vector<string>* logging_directories_list;
1604 const vector<string>& GetLoggingDirectories() {
1605 // Not strictly thread-safe but we're called early in InitGoogle().
1606 if (logging_directories_list == NULL) {
1607 logging_directories_list = new vector<string>;
1609 if ( !FLAGS_log_dir.empty() ) {
1610 // A dir was specified, we should use it
1611 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1613 GetTempDirectories(logging_directories_list);
1616 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1617 logging_directories_list->push_back(tmp);
1618 logging_directories_list->push_back(".\\");
1620 logging_directories_list->push_back("./");
1624 return *logging_directories_list;
1627 void TestOnly_ClearLoggingDirectoriesList() {
1628 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1629 "called from test code.\n");
1630 delete logging_directories_list;
1631 logging_directories_list = NULL;
1634 void GetExistingTempDirectories(vector<string>* list) {
1635 GetTempDirectories(list);
1636 vector<string>::iterator i_dir = list->begin();
1637 while( i_dir != list->end() ) {
1638 // zero arg to access means test for existence; no constant
1639 // defined on windows
1640 if ( access(i_dir->c_str(), 0) ) {
1641 i_dir = list->erase(i_dir);
1648 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1649 #ifdef HAVE_UNISTD_H
1650 struct stat statbuf;
1651 const int kCopyBlockSize = 8 << 10;
1652 char copybuf[kCopyBlockSize];
1653 int64 read_offset, write_offset;
1654 // Don't follow symlinks unless they're our own fd symlinks in /proc
1656 const char *procfd_prefix = "/proc/self/fd/";
1657 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1659 int fd = open(path, flags);
1661 if (errno == EFBIG) {
1662 // The log file in question has got too big for us to open. The
1663 // real fix for this would be to compile logging.cc (or probably
1664 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1666 // Instead just truncate the file to something we can manage
1667 if (truncate(path, 0) == -1) {
1668 PLOG(ERROR) << "Unable to truncate " << path;
1670 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1673 PLOG(ERROR) << "Unable to open " << path;
1678 if (fstat(fd, &statbuf) == -1) {
1679 PLOG(ERROR) << "Unable to fstat()";
1683 // See if the path refers to a regular file bigger than the
1685 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1686 if (statbuf.st_size <= limit) goto out_close_fd;
1687 if (statbuf.st_size <= keep) goto out_close_fd;
1689 // This log file is too large - we need to truncate it
1690 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1692 // Copy the last "keep" bytes of the file to the beginning of the file
1693 read_offset = statbuf.st_size - keep;
1695 int bytesin, bytesout;
1696 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1697 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1698 if (bytesout == -1) {
1699 PLOG(ERROR) << "Unable to write to " << path;
1701 } else if (bytesout != bytesin) {
1702 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1704 read_offset += bytesin;
1705 write_offset += bytesout;
1707 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1709 // Truncate the remainder of the file. If someone else writes to the
1710 // end of the file after our last read() above, we lose their latest
1711 // data. Too bad ...
1712 if (ftruncate(fd, write_offset) == -1) {
1713 PLOG(ERROR) << "Unable to truncate " << path;
1719 LOG(ERROR) << "No log truncation support.";
1723 void TruncateStdoutStderr() {
1724 #ifdef HAVE_UNISTD_H
1725 int64 limit = MaxLogSize() << 20;
1726 int64 keep = 1 << 20;
1727 TruncateLogFile("/proc/self/fd/1", limit, keep);
1728 TruncateLogFile("/proc/self/fd/2", limit, keep);
1730 LOG(ERROR) << "No log truncation support.";
1735 // Helper functions for string comparisons.
1736 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1737 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1738 const char* names) { \
1739 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1740 if (equal == expected) return NULL; \
1745 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1746 return new string(ss.str()); \
1749 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1750 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1751 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1752 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1753 #undef DEFINE_CHECK_STROP_IMPL
1755 int posix_strerror_r(int err, char *buf, size_t len) {
1756 // Sanity check input parameters
1757 if (buf == NULL || len <= 0) {
1762 // Reset buf and errno, and try calling whatever version of strerror_r()
1763 // is implemented by glibc
1765 int old_errno = errno;
1767 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1769 // Both versions set errno on failure
1771 // Should already be there, but better safe than sorry
1777 // POSIX is vague about whether the string will be terminated, although
1778 // is indirectly implies that typically ERANGE will be returned, instead
1779 // of truncating the string. This is different from the GNU implementation.
1780 // We play it safe by always terminating the string explicitly.
1781 buf[len-1] = '\000';
1783 // If the function succeeded, we can use its exit code to determine the
1784 // semantics implemented by glibc
1788 // GNU semantics detected
1793 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
1794 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
1795 // This means an error on MacOSX or FreeBSD.
1799 strncat(buf, rc, len-1);
1805 LogMessageFatal::LogMessageFatal(const char* file, int line) :
1806 LogMessage(file, line, GLOG_FATAL) {}
1808 LogMessageFatal::LogMessageFatal(const char* file, int line,
1809 const CheckOpString& result) :
1810 LogMessage(file, line, result) {}
1812 LogMessageFatal::~LogMessageFatal() {
1819 CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
1820 : stream_(new ostringstream) {
1821 *stream_ << exprtext << " (";
1824 CheckOpMessageBuilder::~CheckOpMessageBuilder() {
1828 ostream* CheckOpMessageBuilder::ForVar2() {
1829 *stream_ << " vs. ";
1833 string* CheckOpMessageBuilder::NewString() {
1835 return new string(stream_->str());
1841 void MakeCheckOpValueString(std::ostream* os, const char& v) {
1842 if (v >= 32 && v <= 126) {
1843 (*os) << "'" << v << "'";
1845 (*os) << "char value " << (short)v;
1850 void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
1851 if (v >= 32 && v <= 126) {
1852 (*os) << "'" << v << "'";
1854 (*os) << "signed char value " << (short)v;
1859 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
1860 if (v >= 32 && v <= 126) {
1861 (*os) << "'" << v << "'";
1863 (*os) << "unsigned char value " << (unsigned short)v;
1867 void InitGoogleLogging(const char* argv0) {
1868 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
1871 void ShutdownGoogleLogging() {
1872 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
1873 LogDestination::DeleteLogDestinations();
1874 delete logging_directories_list;
1875 logging_directories_list = NULL;
1878 _END_GOOGLE_NAMESPACE_