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"
71 using std::ostrstream;
78 using std::ostringstream;
81 // There is no thread annotation support.
82 #define EXCLUSIVE_LOCKS_REQUIRED(mu)
84 static bool BoolFromEnv(const char *varname, bool defval) {
85 const char* const valstr = getenv(varname);
89 return memchr("tTyY1\0", valstr[0], 6) != NULL;
92 GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
93 "log messages go to stderr instead of logfiles");
94 GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
95 "log messages go to stderr in addition to logfiles");
97 GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
98 "Logs can grow very quickly and they are rarely read before they "
99 "need to be evicted from memory. Instead, drop them from memory "
100 "as soon as they are flushed to disk.");
101 _START_GOOGLE_NAMESPACE_
103 static const int64 kPageSize = getpagesize();
105 _END_GOOGLE_NAMESPACE_
108 // By default, errors (including fatal errors) get logged to stderr as
111 // The default is ERROR instead of FATAL so that users can see problems
112 // when they run a program without having to look in another file.
113 DEFINE_int32(stderrthreshold,
114 GOOGLE_NAMESPACE::ERROR,
115 "log messages at or above this level are copied to stderr in "
116 "addition to logfiles. This flag obsoletes --alsologtostderr.");
118 GLOG_DEFINE_string(alsologtoemail, "",
119 "log messages go to these email addresses "
120 "in addition to logfiles");
121 GLOG_DEFINE_bool(log_prefix, true,
122 "Prepend the log prefix to the start of each log line");
123 GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
124 "actually get logged anywhere");
125 GLOG_DEFINE_int32(logbuflevel, 0,
126 "Buffer log messages logged at this level or lower"
127 " (-1 means don't buffer; 0 means buffer INFO only;"
129 GLOG_DEFINE_int32(logbufsecs, 30,
130 "Buffer log messages for at most this many seconds");
131 GLOG_DEFINE_int32(logemaillevel, 999,
132 "Email log messages logged at this level or higher"
133 " (0 means email all; 3 means email FATAL only;"
135 GLOG_DEFINE_string(logmailer, "/bin/mail",
136 "Mailer used to send logging email");
138 // Compute the default value for --log_dir
139 static const char* DefaultLogDir() {
141 env = getenv("GOOGLE_LOG_DIR");
142 if (env != NULL && env[0] != '\0') {
145 env = getenv("TEST_TMPDIR");
146 if (env != NULL && env[0] != '\0') {
152 GLOG_DEFINE_string(log_dir, DefaultLogDir(),
153 "If specified, logfiles are written into this directory instead "
154 "of the default logging directory.");
155 GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
156 "files in this directory");
158 GLOG_DEFINE_int32(max_log_size, 1800,
159 "approx. maximum log file size (in MB). A value of 0 will "
160 "be silently overridden to 1.");
162 GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
163 "Stop attempting to log to disk if the disk is full.");
165 GLOG_DEFINE_string(log_backtrace_at, "",
166 "Emit a backtrace when logging at file:linenum.");
168 // TODO(hamaji): consider windows
169 #define PATH_SEPARATOR '/'
171 static void GetHostName(string* hostname) {
172 #if defined(HAVE_SYS_UTSNAME_H)
174 if (0 != uname(&buf)) {
175 // ensure null termination on failure
176 *buf.nodename = '\0';
178 *hostname = buf.nodename;
179 #elif defined(OS_WINDOWS)
180 char buf[MAX_COMPUTERNAME_LENGTH + 1];
181 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
182 if (GetComputerNameA(buf, &len)) {
188 # warning There is no way to retrieve the host name.
189 *hostname = "(unknown)";
193 _START_GOOGLE_NAMESPACE_
195 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
196 static int32 MaxLogSize() {
197 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
200 // A mutex that allows only one thread to log at a time, to keep things from
201 // getting jumbled. Some other very uncommon logging operations (like
202 // changing the destination file for log messages of a given severity) also
203 // lock this mutex. Please be sure that anybody who might possibly need to
205 static Mutex log_mutex;
207 // Number of messages sent at each severity. Under log_mutex.
208 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
210 // Globally disable log writing (if disk is full)
211 static bool stop_writing = false;
213 const char*const LogSeverityNames[NUM_SEVERITIES] = {
214 "INFO", "WARNING", "ERROR", "FATAL"
217 // Has the user called SetExitOnDFatal(true)?
218 static bool exit_on_dfatal = true;
220 const char* GetLogSeverityName(LogSeverity severity) {
221 return LogSeverityNames[severity];
224 static bool SendEmailInternal(const char*dest, const char *subject,
225 const char*body, bool use_logging);
227 base::Logger::~Logger() {
232 // Encapsulates all file-system related state
233 class LogFileObject : public base::Logger {
235 LogFileObject(LogSeverity severity, const char* base_filename);
238 virtual void Write(bool force_flush, // Should we force a flush here?
239 time_t timestamp, // Timestamp for this entry
243 // Configuration options
244 void SetBasename(const char* basename);
245 void SetExtension(const char* ext);
246 void SetSymlinkBasename(const char* symlink_basename);
248 // Normal flushing routine
249 virtual void Flush();
251 // It is the actual file length for the system loggers,
252 // i.e., INFO, ERROR, etc.
253 virtual uint32 LogSize() {
258 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
259 // can avoid grabbing a lock. Usually Flush() calls it after
261 void FlushUnlocked();
264 static const uint32 kRolloverAttemptFrequency = 0x20;
267 bool base_filename_selected_;
268 string base_filename_;
269 string symlink_basename_;
270 string filename_extension_; // option users can specify (eg to add port#)
272 LogSeverity severity_;
273 uint32 bytes_since_flush_;
275 unsigned int rollover_attempt_;
276 int64 next_flush_time_; // cycle count at which to flush log
278 // Actually create a logfile using the value of base_filename_ and the
279 // supplied argument time_pid_string
280 // REQUIRES: lock_ is held
281 bool CreateLogfile(const char* time_pid_string);
286 class LogDestination {
288 friend class LogMessage;
289 friend void ReprintFatalMessage();
290 friend base::Logger* base::GetLogger(LogSeverity);
291 friend void base::SetLogger(LogSeverity, base::Logger*);
293 // These methods are just forwarded to by their global versions.
294 static void SetLogDestination(LogSeverity severity,
295 const char* base_filename);
296 static void SetLogSymlink(LogSeverity severity,
297 const char* symlink_basename);
298 static void AddLogSink(LogSink *destination);
299 static void RemoveLogSink(LogSink *destination);
300 static void SetLogFilenameExtension(const char* filename_extension);
301 static void SetStderrLogging(LogSeverity min_severity);
302 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
303 static void LogToStderr();
304 // Flush all log files that are at least at the given severity level
305 static void FlushLogFiles(int min_severity);
306 static void FlushLogFilesUnsafe(int min_severity);
308 // we set the maximum size of our packet to be 1400, the logic being
309 // to prevent fragmentation.
310 // Really this number is arbitrary.
311 static const int kNetworkBytes = 1400;
313 static const string& hostname();
315 static void DeleteLogDestinations();
318 LogDestination(LogSeverity severity, const char* base_filename);
319 ~LogDestination() { }
321 // Take a log message of a particular severity and log it to stderr
322 // iff it's of a high enough severity to deserve it.
323 static void MaybeLogToStderr(LogSeverity severity, const char* message,
326 // Take a log message of a particular severity and log it to email
327 // iff it's of a high enough severity to deserve it.
328 static void MaybeLogToEmail(LogSeverity severity, const char* message,
330 // Take a log message of a particular severity and log it to a file
331 // iff the base filename is not "" (which means "don't log to me")
332 static void MaybeLogToLogfile(LogSeverity severity,
334 const char* message, size_t len);
335 // Take a log message of a particular severity and log it to the file
336 // for that severity and also for all files with severity less than
338 static void LogToAllLogfiles(LogSeverity severity,
340 const char* message, size_t len);
342 // Send logging info to all registered sinks.
343 static void LogToSinks(LogSeverity severity,
344 const char *full_filename,
345 const char *base_filename,
347 const struct ::tm* tm_time,
351 // Wait for all registered sinks via WaitTillSent
352 // including the optional one in "data".
353 static void WaitForSinks(LogMessage::LogMessageData* data);
355 static LogDestination* log_destination(LogSeverity severity);
357 LogFileObject fileobject_;
358 base::Logger* logger_; // Either &fileobject_, or wrapper around it
360 static LogDestination* log_destinations_[NUM_SEVERITIES];
361 static LogSeverity email_logging_severity_;
362 static string addresses_;
363 static string hostname_;
365 // arbitrary global logging destinations.
366 static vector<LogSink*>* sinks_;
368 // Protects the vector sinks_,
369 // but not the LogSink objects its elements reference.
370 static Mutex sink_mutex_;
373 LogDestination(const LogDestination&);
374 LogDestination& operator=(const LogDestination&);
377 // Errors do not get logged to email by default.
378 LogSeverity LogDestination::email_logging_severity_ = 99999;
380 string LogDestination::addresses_;
381 string LogDestination::hostname_;
383 vector<LogSink*>* LogDestination::sinks_ = NULL;
384 Mutex LogDestination::sink_mutex_;
387 const string& LogDestination::hostname() {
388 if (hostname_.empty()) {
389 GetHostName(&hostname_);
390 if (hostname_.empty()) {
391 hostname_ = "(unknown)";
397 LogDestination::LogDestination(LogSeverity severity,
398 const char* base_filename)
399 : fileobject_(severity, base_filename),
400 logger_(&fileobject_) {
403 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
404 // assume we have the log_mutex or we simply don't care
406 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
407 LogDestination* log = log_destination(i);
409 // Flush the base fileobject_ logger directly instead of going
410 // through any wrappers to reduce chance of deadlock.
411 log->fileobject_.FlushUnlocked();
416 inline void LogDestination::FlushLogFiles(int min_severity) {
417 // Prevent any subtle race conditions by wrapping a mutex lock around
419 MutexLock l(&log_mutex);
420 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
421 LogDestination* log = log_destination(i);
423 log->logger_->Flush();
428 inline void LogDestination::SetLogDestination(LogSeverity severity,
429 const char* base_filename) {
430 assert(severity >= 0 && severity < NUM_SEVERITIES);
431 // Prevent any subtle race conditions by wrapping a mutex lock around
433 MutexLock l(&log_mutex);
434 log_destination(severity)->fileobject_.SetBasename(base_filename);
437 inline void LogDestination::SetLogSymlink(LogSeverity severity,
438 const char* symlink_basename) {
439 CHECK_GE(severity, 0);
440 CHECK_LT(severity, NUM_SEVERITIES);
441 MutexLock l(&log_mutex);
442 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
445 inline void LogDestination::AddLogSink(LogSink *destination) {
446 // Prevent any subtle race conditions by wrapping a mutex lock around
448 MutexLock l(&sink_mutex_);
449 if (!sinks_) sinks_ = new vector<LogSink*>;
450 sinks_->push_back(destination);
453 inline void LogDestination::RemoveLogSink(LogSink *destination) {
454 // Prevent any subtle race conditions by wrapping a mutex lock around
456 MutexLock l(&sink_mutex_);
457 // This doesn't keep the sinks in order, but who cares?
459 for (int i = sinks_->size() - 1; i >= 0; i--) {
460 if ((*sinks_)[i] == destination) {
461 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
469 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
470 // Prevent any subtle race conditions by wrapping a mutex lock around
472 MutexLock l(&log_mutex);
473 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
474 log_destination(severity)->fileobject_.SetExtension(ext);
478 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
479 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
480 // Prevent any subtle race conditions by wrapping a mutex lock around
482 MutexLock l(&log_mutex);
483 FLAGS_stderrthreshold = min_severity;
486 inline void LogDestination::LogToStderr() {
487 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
488 // SetLogDestination already do the locking!
489 SetStderrLogging(0); // thus everything is "also" logged to stderr
490 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
491 SetLogDestination(i, ""); // "" turns off logging to a logfile
495 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
496 const char* addresses) {
497 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
498 // Prevent any subtle race conditions by wrapping a mutex lock around
500 MutexLock l(&log_mutex);
501 LogDestination::email_logging_severity_ = min_severity;
502 LogDestination::addresses_ = addresses;
505 static void WriteToStderr(const char* message, size_t len) {
506 // Avoid using cerr from this module since we may get called during
507 // exit code, and cerr may be partially or fully destroyed by then.
508 write(STDERR_FILENO, message, len);
511 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
512 const char* message, size_t len) {
513 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
514 WriteToStderr(message, len);
516 // On Windows, also output to the debugger
517 ::OutputDebugStringA(string(message,len).c_str());
523 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
524 const char* message, size_t len) {
525 if (severity >= email_logging_severity_ ||
526 severity >= FLAGS_logemaillevel) {
527 string to(FLAGS_alsologtoemail);
528 if (!addresses_.empty()) {
534 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
535 glog_internal_namespace_::ProgramInvocationShortName());
536 string body(hostname());
538 body.append(message, len);
540 // should NOT use SendEmail(). The caller of this function holds the
541 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
542 // acquire the log_mutex object. Use SendEmailInternal() and set
543 // use_logging to false.
544 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
549 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
553 const bool should_flush = severity > FLAGS_logbuflevel;
554 LogDestination* destination = log_destination(severity);
555 destination->logger_->Write(should_flush, timestamp, message, len);
558 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
563 if ( FLAGS_logtostderr ) // global flag: never log to file
564 WriteToStderr(message, len);
566 for (int i = severity; i >= 0; --i)
567 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
571 inline void LogDestination::LogToSinks(LogSeverity severity,
572 const char *full_filename,
573 const char *base_filename,
575 const struct ::tm* tm_time,
577 size_t message_len) {
578 ReaderMutexLock l(&sink_mutex_);
580 for (int i = sinks_->size() - 1; i >= 0; i--) {
581 (*sinks_)[i]->send(severity, full_filename, base_filename,
582 line, tm_time, message, message_len);
587 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
588 ReaderMutexLock l(&sink_mutex_);
590 for (int i = sinks_->size() - 1; i >= 0; i--) {
591 (*sinks_)[i]->WaitTillSent();
594 const bool send_to_sink =
595 (data->send_method_ == &LogMessage::SendToSink) ||
596 (data->send_method_ == &LogMessage::SendToSinkAndLog);
597 if (send_to_sink && data->sink_ != NULL) {
598 data->sink_->WaitTillSent();
602 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
604 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
605 assert(severity >=0 && severity < NUM_SEVERITIES);
606 if (!log_destinations_[severity]) {
607 log_destinations_[severity] = new LogDestination(severity, NULL);
609 return log_destinations_[severity];
612 void LogDestination::DeleteLogDestinations() {
613 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
614 delete log_destinations_[severity];
615 log_destinations_[severity] = NULL;
621 LogFileObject::LogFileObject(LogSeverity severity,
622 const char* base_filename)
623 : base_filename_selected_(base_filename != NULL),
624 base_filename_((base_filename != NULL) ? base_filename : ""),
625 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
626 filename_extension_(),
629 bytes_since_flush_(0),
631 rollover_attempt_(kRolloverAttemptFrequency-1),
632 next_flush_time_(0) {
633 assert(severity >= 0);
634 assert(severity < NUM_SEVERITIES);
637 LogFileObject::~LogFileObject() {
645 void LogFileObject::SetBasename(const char* basename) {
647 base_filename_selected_ = true;
648 if (base_filename_ != basename) {
649 // Get rid of old log file since we are changing names
653 rollover_attempt_ = kRolloverAttemptFrequency-1;
655 base_filename_ = basename;
659 void LogFileObject::SetExtension(const char* ext) {
661 if (filename_extension_ != ext) {
662 // Get rid of old log file since we are changing names
666 rollover_attempt_ = kRolloverAttemptFrequency-1;
668 filename_extension_ = ext;
672 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
674 symlink_basename_ = symlink_basename;
677 void LogFileObject::Flush() {
682 void LogFileObject::FlushUnlocked(){
685 bytes_since_flush_ = 0;
687 // Figure out when we are due for another flush.
688 const int64 next = (FLAGS_logbufsecs
689 * static_cast<int64>(1000000)); // in usec
690 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
693 bool LogFileObject::CreateLogfile(const char* time_pid_string) {
694 string string_filename = base_filename_+filename_extension_+
696 const char* filename = string_filename.c_str();
697 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
698 if (fd == -1) return false;
700 // Mark the file close-on-exec. We don't really care if this fails
701 fcntl(fd, F_SETFD, FD_CLOEXEC);
704 file_ = fdopen(fd, "a"); // Make a FILE*.
705 if (file_ == NULL) { // Man, we're screwed!
707 unlink(filename); // Erase the half-baked evidence: an unusable log file
711 // We try to create a symlink called <program_name>.<severity>,
712 // which is easier to use. (Every time we create a new logfile,
713 // we destroy the old symlink and create a new one, so it always
714 // points to the latest logfile.) If it fails, we're sad but it's
716 if (!symlink_basename_.empty()) {
717 // take directory from filename
718 const char* slash = strrchr(filename, PATH_SEPARATOR);
719 const string linkname =
720 symlink_basename_ + '.' + LogSeverityNames[severity_];
722 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
723 linkpath += linkname;
724 unlink(linkpath.c_str()); // delete old one if it exists
726 // We must have unistd.h.
728 // Make the symlink be relative (in the same dir) so that if the
729 // entire log directory gets relocated the link is still valid.
730 const char *linkdest = slash ? (slash + 1) : filename;
731 symlink(linkdest, linkpath.c_str()); // silently ignore failures
733 // Make an additional link to the log file in a place specified by
734 // FLAGS_log_link, if indicated
735 if (!FLAGS_log_link.empty()) {
736 linkpath = FLAGS_log_link + "/" + linkname;
737 unlink(linkpath.c_str()); // delete old one if it exists
738 symlink(filename, linkpath.c_str()); // silently ignore failures
743 return true; // Everything worked
746 void LogFileObject::Write(bool force_flush,
752 // We don't log if the base_name_ is "" (which means "don't write")
753 if (base_filename_selected_ && base_filename_.empty()) {
757 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
759 if (file_ != NULL) fclose(file_);
761 file_length_ = bytes_since_flush_ = 0;
762 rollover_attempt_ = kRolloverAttemptFrequency-1;
765 // If there's no destination file, make one before outputting
767 // Try to rollover the log file every 32 log messages. The only time
768 // this could matter would be when we have trouble creating the log
769 // file. If that happens, we'll lose lots of log messages, of course!
770 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
771 rollover_attempt_ = 0;
774 localtime_r(×tamp, &tm_time);
776 // The logfile's filename will have the date/time & pid in it
777 char time_pid_string[256]; // More than enough chars for time, pid, \0
778 ostrstream time_pid_stream(time_pid_string, sizeof(time_pid_string));
779 time_pid_stream.fill('0');
780 time_pid_stream << 1900+tm_time.tm_year
781 << setw(2) << 1+tm_time.tm_mon
782 << setw(2) << tm_time.tm_mday
784 << setw(2) << tm_time.tm_hour
785 << setw(2) << tm_time.tm_min
786 << setw(2) << tm_time.tm_sec
788 << GetMainThreadPid()
791 if (base_filename_selected_) {
792 if (!CreateLogfile(time_pid_string)) {
793 perror("Could not create log file");
794 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", time_pid_string);
798 // If no base filename for logs of this severity has been set, use a
799 // default base filename of
800 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
801 // logfiles will have names like
802 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
803 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
804 // and 4354 is the pid of the logging process. The date & time reflect
805 // when the file was created for output.
807 // Where does the file get put? Successively try the directories
809 string stripped_filename(
810 glog_internal_namespace_::ProgramInvocationShortName());
812 GetHostName(&hostname);
814 string uidname = MyUserName();
815 // We should not call CHECK() here because this function can be
816 // called after holding on to log_mutex. We don't want to
817 // attempt to hold on to the same mutex, and get into a
818 // deadlock. Simply use a name like invalid-user.
819 if (uidname.empty()) uidname = "invalid-user";
821 stripped_filename = stripped_filename+'.'+hostname+'.'
823 +LogSeverityNames[severity_]+'.';
824 // We're going to (potentially) try to put logs in several different dirs
825 const vector<string> & log_dirs = GetLoggingDirectories();
827 // Go through the list of dirs, and try to create the log file in each
828 // until we succeed or run out of options
829 bool success = false;
830 for (vector<string>::const_iterator dir = log_dirs.begin();
831 dir != log_dirs.end();
833 base_filename_ = *dir + "/" + stripped_filename;
834 if ( CreateLogfile(time_pid_string) ) {
839 // If we never succeeded, we have to give up
840 if ( success == false ) {
841 perror("Could not create logging file");
842 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", time_pid_string);
847 // Write a header message into the log file
848 char file_header_string[512]; // Enough chars for time and binary info
849 ostrstream file_header_stream(file_header_string,
850 sizeof(file_header_string));
851 file_header_stream.fill('0');
852 file_header_stream << "Log file created at: "
853 << 1900+tm_time.tm_year << '/'
854 << setw(2) << 1+tm_time.tm_mon << '/'
855 << setw(2) << tm_time.tm_mday
857 << setw(2) << tm_time.tm_hour << ':'
858 << setw(2) << tm_time.tm_min << ':'
859 << setw(2) << tm_time.tm_sec << '\n'
860 << "Running on machine: "
861 << LogDestination::hostname() << '\n'
862 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
863 << "threadid file:line] msg" << '\n'
865 int header_len = strlen(file_header_string);
866 fwrite(file_header_string, 1, header_len, file_);
867 file_length_ += header_len;
868 bytes_since_flush_ += header_len;
872 if ( !stop_writing ) {
873 // fwrite() doesn't return an error when the disk is full, for
874 // messages that are less than 4096 bytes. When the disk is full,
875 // it returns the message length for messages that are less than
876 // 4096 bytes. fwrite() returns 4096 for message lengths that are
877 // greater than 4096, thereby indicating an error.
879 fwrite(message, 1, message_len, file_);
880 if ( FLAGS_stop_logging_if_full_disk &&
881 errno == ENOSPC ) { // disk full, stop writing to disk
882 stop_writing = true; // until the disk is
885 file_length_ += message_len;
886 bytes_since_flush_ += message_len;
889 if ( CycleClock_Now() >= next_flush_time_ )
890 stop_writing = false; // check to see if disk has free space.
891 return; // no need to flush
894 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
895 // or every "FLAGS_logbufsecs" seconds.
897 (bytes_since_flush_ >= 1000000) ||
898 (CycleClock_Now() >= next_flush_time_) ) {
901 if (FLAGS_drop_log_memory) {
902 if (file_length_ >= logging::kPageSize) {
903 // don't evict the most recent page
904 uint32 len = file_length_ & ~(logging::kPageSize - 1);
905 posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
914 // An arbitrary limit on the length of a single log message. This
915 // is so that streaming can be done more efficiently.
916 const size_t LogMessage::kMaxLogMessageLen = 30000;
918 // Static log data space to avoid alloc failures in a LOG(FATAL)
920 // Since multiple threads may call LOG(FATAL), and we want to preserve
921 // the data from the first call, we allocate two sets of space. One
922 // for exclusive use by the first thread, and one for shared use by
923 // all other threads.
924 static Mutex fatal_msg_lock;
925 static CrashReason crash_reason;
926 static bool fatal_msg_exclusive = true;
927 static char fatal_msg_buf_exclusive[LogMessage::kMaxLogMessageLen+1];
928 static char fatal_msg_buf_shared[LogMessage::kMaxLogMessageLen+1];
929 static LogMessage::LogStream fatal_msg_stream_exclusive(
930 fatal_msg_buf_exclusive, LogMessage::kMaxLogMessageLen, 0);
931 static LogMessage::LogStream fatal_msg_stream_shared(
932 fatal_msg_buf_shared, LogMessage::kMaxLogMessageLen, 0);
933 LogMessage::LogMessageData LogMessage::fatal_msg_data_exclusive_;
934 LogMessage::LogMessageData LogMessage::fatal_msg_data_shared_;
936 LogMessage::LogMessageData::~LogMessageData() {
938 delete stream_alloc_;
941 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
942 int ctr, void (LogMessage::*send_method)()) {
943 Init(file, line, severity, send_method);
944 data_->stream_->set_ctr(ctr);
947 LogMessage::LogMessage(const char* file, int line,
948 const CheckOpString& result) {
949 Init(file, line, FATAL, &LogMessage::SendToLog);
950 stream() << "Check failed: " << (*result.str_) << " ";
953 LogMessage::LogMessage(const char* file, int line) {
954 Init(file, line, INFO, &LogMessage::SendToLog);
957 LogMessage::LogMessage(const char* file, int line, LogSeverity severity) {
958 Init(file, line, severity, &LogMessage::SendToLog);
961 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
962 LogSink* sink, bool also_send_to_log) {
963 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
964 &LogMessage::SendToSink);
965 data_->sink_ = sink; // override Init()'s setting to NULL
968 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
969 vector<string> *outvec) {
970 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
971 data_->outvec_ = outvec; // override Init()'s setting to NULL
974 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
976 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
977 data_->message_ = message; // override Init()'s setting to NULL
980 void LogMessage::Init(const char* file,
982 LogSeverity severity,
983 void (LogMessage::*send_method)()) {
985 if (severity != FATAL || !exit_on_dfatal) {
986 allocated_ = new LogMessageData();
988 data_->buf_ = new char[kMaxLogMessageLen+1];
989 data_->message_text_ = data_->buf_;
990 data_->stream_alloc_ =
991 new LogStream(data_->message_text_, kMaxLogMessageLen, 0);
992 data_->stream_ = data_->stream_alloc_;
993 data_->first_fatal_ = false;
995 MutexLock l(&fatal_msg_lock);
996 if (fatal_msg_exclusive) {
997 fatal_msg_exclusive = false;
998 data_ = &fatal_msg_data_exclusive_;
999 data_->message_text_ = fatal_msg_buf_exclusive;
1000 data_->stream_ = &fatal_msg_stream_exclusive;
1001 data_->first_fatal_ = true;
1003 data_ = &fatal_msg_data_shared_;
1004 data_->message_text_ = fatal_msg_buf_shared;
1005 data_->stream_ = &fatal_msg_stream_shared;
1006 data_->first_fatal_ = false;
1008 data_->stream_alloc_ = NULL;
1012 data_->preserved_errno_ = errno;
1013 data_->severity_ = severity;
1014 data_->line_ = line;
1015 data_->send_method_ = send_method;
1016 data_->sink_ = NULL;
1017 data_->outvec_ = NULL;
1018 WallTime now = WallTime_Now();
1019 data_->timestamp_ = static_cast<time_t>(now);
1020 localtime_r(&data_->timestamp_, &data_->tm_time_);
1021 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1022 RawLog__SetLastTime(data_->tm_time_, usecs);
1024 data_->num_chars_to_log_ = 0;
1025 data_->num_chars_to_syslog_ = 0;
1026 data_->basename_ = const_basename(file);
1027 data_->fullname_ = file;
1028 data_->has_been_flushed_ = false;
1030 // If specified, prepend a prefix to each line. For example:
1031 // I1018 160715 f5d4fbb0 logging.cc:1153]
1032 // (log level, GMT month, date, time, thread_id, file basename, line)
1033 // We exclude the thread_id for the default thread.
1034 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1035 stream() << LogSeverityNames[severity][0]
1036 << setw(2) << 1+data_->tm_time_.tm_mon
1037 << setw(2) << data_->tm_time_.tm_mday
1039 << setw(2) << data_->tm_time_.tm_hour << ':'
1040 << setw(2) << data_->tm_time_.tm_min << ':'
1041 << setw(2) << data_->tm_time_.tm_sec << "."
1044 << setfill(' ') << setw(5)
1045 << static_cast<unsigned int>(GetTID()) << setfill('0')
1047 << data_->basename_ << ':' << data_->line_ << "] ";
1049 data_->num_prefix_chars_ = data_->stream_->pcount();
1051 if (!FLAGS_log_backtrace_at.empty()) {
1053 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1054 #ifdef HAVE_STACKTRACE
1055 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1057 DumpStackTraceToString(&stacktrace);
1058 stream() << " (stacktrace:\n" << stacktrace << ") ";
1064 LogMessage::~LogMessage() {
1069 // Flush buffered message, called by the destructor, or any other function
1070 // that needs to synchronize the log.
1071 void LogMessage::Flush() {
1072 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1075 data_->num_chars_to_log_ = data_->stream_->pcount();
1076 data_->num_chars_to_syslog_ =
1077 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1079 // Do we need to add a \n to the end of this message?
1080 bool append_newline =
1081 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1082 char original_final_char = '\0';
1084 // If we do need to add a \n, we'll do it by violating the memory of the
1085 // ostrstream buffer. This is quick, and we'll make sure to undo our
1086 // modification before anything else is done with the ostrstream. It
1087 // would be preferable not to do things this way, but it seems to be
1088 // the best way to deal with this.
1089 if (append_newline) {
1090 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1091 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1094 // Prevent any subtle race conditions by wrapping a mutex lock around
1095 // the actual logging action per se.
1097 MutexLock l(&log_mutex);
1098 (this->*(data_->send_method_))();
1099 ++num_messages_[static_cast<int>(data_->severity_)];
1101 LogDestination::WaitForSinks(data_);
1103 if (append_newline) {
1104 // Fix the ostrstream back how it was before we screwed with it.
1105 // It's 99.44% certain that we don't need to worry about doing this.
1106 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1109 // If errno was already set before we enter the logging call, we'll
1110 // set it back to that value when we return from the logging call.
1111 // It happens often that we log an error message after a syscall
1112 // failure, which can potentially set the errno to some other
1113 // values. We would like to preserve the original errno.
1114 if (data_->preserved_errno_ != 0) {
1115 errno = data_->preserved_errno_;
1118 // Note that this message is now safely logged. If we're asked to flush
1119 // again, as a result of destruction, say, we'll do nothing on future calls.
1120 data_->has_been_flushed_ = true;
1123 // Copy of first FATAL log message so that we can print it out again
1124 // after all the stack traces. To preserve legacy behavior, we don't
1125 // use fatal_msg_buf_exclusive.
1126 static time_t fatal_time;
1127 static char fatal_message[256];
1129 void ReprintFatalMessage() {
1130 if (fatal_message[0]) {
1131 const int n = strlen(fatal_message);
1132 if (!FLAGS_logtostderr) {
1133 // Also write to stderr
1134 WriteToStderr(fatal_message, n);
1136 LogDestination::LogToAllLogfiles(ERROR, fatal_time, fatal_message, n);
1140 // L >= log_mutex (callers must hold the log_mutex).
1141 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1142 static bool already_warned_before_initgoogle = false;
1144 log_mutex.AssertHeld();
1146 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1147 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1149 // Messages of a given severity get logged to lower severity logs, too
1151 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1152 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1153 "written to STDERR\n";
1154 WriteToStderr(w, strlen(w));
1155 already_warned_before_initgoogle = true;
1158 // global flag: never log to file if set. Also -- don't log to a
1159 // file if we haven't parsed the command line flags to get the
1161 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1162 WriteToStderr(data_->message_text_, data_->num_chars_to_log_);
1164 // this could be protected by a flag if necessary.
1165 LogDestination::LogToSinks(data_->severity_,
1166 data_->fullname_, data_->basename_,
1167 data_->line_, &data_->tm_time_,
1168 data_->message_text_ + data_->num_prefix_chars_,
1169 (data_->num_chars_to_log_ -
1170 data_->num_prefix_chars_ - 1));
1173 // log this message to all log files of severity <= severity_
1174 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1175 data_->message_text_,
1176 data_->num_chars_to_log_);
1178 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1179 data_->num_chars_to_log_);
1180 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1181 data_->num_chars_to_log_);
1182 LogDestination::LogToSinks(data_->severity_,
1183 data_->fullname_, data_->basename_,
1184 data_->line_, &data_->tm_time_,
1185 data_->message_text_ + data_->num_prefix_chars_,
1186 (data_->num_chars_to_log_
1187 - data_->num_prefix_chars_ - 1));
1188 // NOTE: -1 removes trailing \n
1191 // If we log a FATAL message, flush all the log destinations, then toss
1192 // a signal for others to catch. We leave the logs in a state that
1193 // someone else can use them (as long as they flush afterwards)
1194 if (data_->severity_ == FATAL && exit_on_dfatal) {
1195 if (data_->first_fatal_) {
1196 // Store crash information so that it is accessible from within signal
1197 // handlers that may be invoked later.
1198 RecordCrashReason(&crash_reason);
1199 SetCrashReason(&crash_reason);
1201 // Store shortened fatal message for other logs and GWQ status
1202 const int copy = min<int>(data_->num_chars_to_log_,
1203 sizeof(fatal_message)-1);
1204 memcpy(fatal_message, data_->message_text_, copy);
1205 fatal_message[copy] = '\0';
1206 fatal_time = data_->timestamp_;
1209 if (!FLAGS_logtostderr) {
1210 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1211 if ( LogDestination::log_destinations_[i] )
1212 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1216 // release the lock that our caller (directly or indirectly)
1217 // LogMessage::~LogMessage() grabbed so that signal handlers
1218 // can use the logging facility. Alternately, we could add
1219 // an entire unsafe logging interface to bypass locking
1220 // for signal handlers but this seems simpler.
1222 LogDestination::WaitForSinks(data_);
1224 const char* message = "*** Check failure stack trace: ***\n";
1225 write(STDERR_FILENO, message, strlen(message));
1230 void LogMessage::RecordCrashReason(
1231 glog_internal_namespace_::CrashReason* reason) {
1232 reason->filename = fatal_msg_data_exclusive_.fullname_;
1233 reason->line_number = fatal_msg_data_exclusive_.line_;
1234 reason->message = fatal_msg_buf_exclusive +
1235 fatal_msg_data_exclusive_.num_prefix_chars_;
1236 #ifdef HAVE_STACKTRACE
1237 // Retrieve the stack trace, omitting the logging frames that got us here.
1238 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1244 static void logging_fail() {
1245 #if defined(_DEBUG) && defined(_MSC_VER)
1246 // When debugging on windows, avoid the obnoxious dialog and make
1247 // it possible to continue past a LOG(FATAL) in the debugger
1254 #ifdef HAVE___ATTRIBUTE__
1255 GOOGLE_GLOG_DLL_DECL
1256 void (*g_logging_fail_func)() __attribute__((noreturn)) = &logging_fail;
1258 GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)() = &logging_fail;
1261 void InstallFailureFunction(void (*fail_func)()) {
1262 g_logging_fail_func = fail_func;
1265 void LogMessage::Fail() {
1266 g_logging_fail_func();
1269 // L >= log_mutex (callers must hold the log_mutex).
1270 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1271 if (data_->sink_ != NULL) {
1272 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1273 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1274 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1275 data_->line_, &data_->tm_time_,
1276 data_->message_text_ + data_->num_prefix_chars_,
1277 (data_->num_chars_to_log_ -
1278 data_->num_prefix_chars_ - 1));
1282 // L >= log_mutex (callers must hold the log_mutex).
1283 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1288 // L >= log_mutex (callers must hold the log_mutex).
1289 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1290 if (data_->outvec_ != NULL) {
1291 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1292 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1293 // Omit prefix of message and trailing newline when recording in outvec_.
1294 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1295 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1296 data_->outvec_->push_back(string(start, len));
1302 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1303 if (data_->message_ != NULL) {
1304 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1305 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1306 // Omit prefix of message and trailing newline when writing to message_.
1307 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1308 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1309 data_->message_->assign(start, len);
1314 // L >= log_mutex (callers must hold the log_mutex).
1315 void LogMessage::SendToSyslogAndLog() {
1316 #ifdef HAVE_SYSLOG_H
1317 // Before any calls to syslog(), make a single call to openlog()
1318 static bool openlog_already_called = false;
1319 if (!openlog_already_called) {
1320 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1321 LOG_CONS | LOG_NDELAY | LOG_PID,
1323 openlog_already_called = true;
1326 // This array maps Google severity levels to syslog levels
1327 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1328 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1329 int(data_->num_chars_to_syslog_),
1330 data_->message_text_ + data_->num_prefix_chars_);
1333 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1337 base::Logger* base::GetLogger(LogSeverity severity) {
1338 MutexLock l(&log_mutex);
1339 return LogDestination::log_destination(severity)->logger_;
1342 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1343 MutexLock l(&log_mutex);
1344 LogDestination::log_destination(severity)->logger_ = logger;
1347 // L < log_mutex. Acquires and releases mutex_.
1348 int64 LogMessage::num_messages(int severity) {
1349 MutexLock l(&log_mutex);
1350 return num_messages_[severity];
1353 // Output the COUNTER value. This is only valid if ostream is a
1355 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1356 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1357 CHECK(log == log->self());
1362 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1363 LogSeverity severity, int ctr,
1364 void (LogMessage::*send_method)())
1365 : LogMessage(file, line, severity, ctr, send_method) {
1368 ErrnoLogMessage::~ErrnoLogMessage() {
1369 // Don't access errno directly because it may have been altered
1370 // while streaming the message.
1372 posix_strerror_r(preserved_errno(), buf, sizeof(buf));
1373 stream() << ": " << buf << " [" << preserved_errno() << "]";
1376 void FlushLogFiles(LogSeverity min_severity) {
1377 LogDestination::FlushLogFiles(min_severity);
1380 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1381 LogDestination::FlushLogFilesUnsafe(min_severity);
1384 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1385 LogDestination::SetLogDestination(severity, base_filename);
1388 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1389 LogDestination::SetLogSymlink(severity, symlink_basename);
1392 LogSink::~LogSink() {
1395 void LogSink::WaitTillSent() {
1399 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1400 const struct ::tm* tm_time,
1401 const char* message, size_t message_len) {
1402 ostringstream stream(string(message, message_len));
1405 // FIXME(jrvb): Updating this to use the correct value for usecs
1406 // requires changing the signature for both this method and
1407 // LogSink::send(). This change needs to be done in a separate CL
1408 // so subclasses of LogSink can be updated at the same time.
1411 stream << LogSeverityNames[severity][0]
1412 << setw(2) << 1+tm_time->tm_mon
1413 << setw(2) << tm_time->tm_mday
1415 << setw(2) << tm_time->tm_hour << ':'
1416 << setw(2) << tm_time->tm_min << ':'
1417 << setw(2) << tm_time->tm_sec << '.'
1420 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1422 << file << ':' << line << "] ";
1424 stream << string(message, message_len);
1425 return stream.str();
1428 void AddLogSink(LogSink *destination) {
1429 LogDestination::AddLogSink(destination);
1432 void RemoveLogSink(LogSink *destination) {
1433 LogDestination::RemoveLogSink(destination);
1436 void SetLogFilenameExtension(const char* ext) {
1437 LogDestination::SetLogFilenameExtension(ext);
1440 void SetStderrLogging(LogSeverity min_severity) {
1441 LogDestination::SetStderrLogging(min_severity);
1444 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1445 LogDestination::SetEmailLogging(min_severity, addresses);
1448 void LogToStderr() {
1449 LogDestination::LogToStderr();
1453 namespace internal {
1455 bool GetExitOnDFatal() {
1456 MutexLock l(&log_mutex);
1457 return exit_on_dfatal;
1460 // Determines whether we exit the program for a LOG(DFATAL) message in
1461 // debug mode. It does this by skipping the call to Fail/FailQuietly.
1462 // This is intended for testing only.
1464 // This can have some effects on LOG(FATAL) as well. Failure messages
1465 // are always allocated (rather than sharing a buffer), the crash
1466 // reason is not recorded, the "gwq" status message is not updated,
1467 // and the stack trace is not recorded. The LOG(FATAL) *will* still
1468 // exit the program. Since this function is used only in testing,
1469 // these differences are acceptable.
1470 void SetExitOnDFatal(bool value) {
1471 MutexLock l(&log_mutex);
1472 exit_on_dfatal = value;
1475 } // namespace internal
1478 // use_logging controls whether the logging functions LOG/VLOG are used
1479 // to log errors. It should be set to false when the caller holds the
1481 static bool SendEmailInternal(const char*dest, const char *subject,
1482 const char*body, bool use_logging) {
1483 if (dest && *dest) {
1484 if ( use_logging ) {
1485 VLOG(1) << "Trying to send TITLE:" << subject
1486 << " BODY:" << body << " to " << dest;
1488 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1489 subject, body, dest);
1493 FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1494 FILE* pipe = popen(cmd.c_str(), "w");
1496 // Add the body if we have one
1498 fwrite(body, sizeof(char), strlen(body), pipe);
1499 bool ok = pclose(pipe) != -1;
1501 if ( use_logging ) {
1503 posix_strerror_r(errno, buf, sizeof(buf));
1504 LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf;
1507 posix_strerror_r(errno, buf, sizeof(buf));
1508 fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf);
1513 if ( use_logging ) {
1514 LOG(ERROR) << "Unable to send mail to " << dest;
1516 fprintf(stderr, "Unable to send mail to %s\n", dest);
1523 bool SendEmail(const char*dest, const char *subject, const char*body){
1524 return SendEmailInternal(dest, subject, body, true);
1527 static void GetTempDirectories(vector<string>* list) {
1530 // On windows we'll try to find a directory in this order:
1531 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1534 // C:/WINDOWS/ or C:/WINNT/
1537 if (GetTempPathA(MAX_PATH, tmp))
1538 list->push_back(tmp);
1539 list->push_back("C:\\tmp\\");
1540 list->push_back("C:\\temp\\");
1542 // Directories, in order of preference. If we find a dir that
1543 // exists, we stop adding other less-preferred dirs
1544 const char * candidates[] = {
1545 // Non-null only during unittest/regtest
1546 getenv("TEST_TMPDIR"),
1548 // Explicitly-supplied temp dirs
1549 getenv("TMPDIR"), getenv("TMP"),
1551 // If all else fails
1555 for (int i = 0; i < ARRAYSIZE(candidates); i++) {
1556 const char *d = candidates[i];
1557 if (!d) continue; // Empty env var
1559 // Make sure we don't surprise anyone who's expecting a '/'
1561 if (dstr[dstr.size() - 1] != '/') {
1564 list->push_back(dstr);
1566 struct stat statbuf;
1567 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1568 // We found a dir that exists - we're done.
1576 static vector<string>* logging_directories_list;
1578 const vector<string>& GetLoggingDirectories() {
1579 // Not strictly thread-safe but we're called early in InitGoogle().
1580 if (logging_directories_list == NULL) {
1581 logging_directories_list = new vector<string>;
1583 if ( !FLAGS_log_dir.empty() ) {
1584 // A dir was specified, we should use it
1585 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1587 GetTempDirectories(logging_directories_list);
1590 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1591 logging_directories_list->push_back(tmp);
1592 logging_directories_list->push_back(".\\");
1594 logging_directories_list->push_back("./");
1598 return *logging_directories_list;
1601 void TestOnly_ClearLoggingDirectoriesList() {
1602 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1603 "called from test code.\n");
1604 delete logging_directories_list;
1605 logging_directories_list = NULL;
1608 void GetExistingTempDirectories(vector<string>* list) {
1609 GetTempDirectories(list);
1610 vector<string>::iterator i_dir = list->begin();
1611 while( i_dir != list->end() ) {
1612 // zero arg to access means test for existence; no constant
1613 // defined on windows
1614 if ( access(i_dir->c_str(), 0) ) {
1615 i_dir = list->erase(i_dir);
1622 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1623 #ifdef HAVE_UNISTD_H
1624 struct stat statbuf;
1625 const int kCopyBlockSize = 8 << 10;
1626 char copybuf[kCopyBlockSize];
1627 int64 read_offset, write_offset;
1628 // Don't follow symlinks unless they're our own fd symlinks in /proc
1630 const char *procfd_prefix = "/proc/self/fd/";
1631 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1633 int fd = open(path, flags);
1635 if (errno == EFBIG) {
1636 // The log file in question has got too big for us to open. The
1637 // real fix for this would be to compile logging.cc (or probably
1638 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1640 // Instead just truncate the file to something we can manage
1641 if (truncate(path, 0) == -1) {
1642 PLOG(ERROR) << "Unable to truncate " << path;
1644 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1647 PLOG(ERROR) << "Unable to open " << path;
1652 if (fstat(fd, &statbuf) == -1) {
1653 PLOG(ERROR) << "Unable to fstat()";
1657 // See if the path refers to a regular file bigger than the
1659 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1660 if (statbuf.st_size <= limit) goto out_close_fd;
1661 if (statbuf.st_size <= keep) goto out_close_fd;
1663 // This log file is too large - we need to truncate it
1664 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1666 // Copy the last "keep" bytes of the file to the beginning of the file
1667 read_offset = statbuf.st_size - keep;
1669 int bytesin, bytesout;
1670 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1671 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1672 if (bytesout == -1) {
1673 PLOG(ERROR) << "Unable to write to " << path;
1675 } else if (bytesout != bytesin) {
1676 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1678 read_offset += bytesin;
1679 write_offset += bytesout;
1681 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1683 // Truncate the remainder of the file. If someone else writes to the
1684 // end of the file after our last read() above, we lose their latest
1685 // data. Too bad ...
1686 if (ftruncate(fd, write_offset) == -1) {
1687 PLOG(ERROR) << "Unable to truncate " << path;
1693 LOG(ERROR) << "No log truncation support.";
1697 void TruncateStdoutStderr() {
1698 #ifdef HAVE_UNISTD_H
1699 int64 limit = MaxLogSize() << 20;
1700 int64 keep = 1 << 20;
1701 TruncateLogFile("/proc/self/fd/1", limit, keep);
1702 TruncateLogFile("/proc/self/fd/2", limit, keep);
1704 LOG(ERROR) << "No log truncation support.";
1709 // Helper functions for string comparisons.
1710 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1711 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1712 const char* names) { \
1713 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1714 if (equal == expected) return NULL; \
1719 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1720 return new string(ss.str(), ss.pcount()); \
1723 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1724 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1725 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1726 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1727 #undef DEFINE_CHECK_STROP_IMPL
1729 int posix_strerror_r(int err, char *buf, size_t len) {
1730 // Sanity check input parameters
1731 if (buf == NULL || len <= 0) {
1736 // Reset buf and errno, and try calling whatever version of strerror_r()
1737 // is implemented by glibc
1739 int old_errno = errno;
1741 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1743 // Both versions set errno on failure
1745 // Should already be there, but better safe than sorry
1751 // POSIX is vague about whether the string will be terminated, although
1752 // is indirectly implies that typically ERANGE will be returned, instead
1753 // of truncating the string. This is different from the GNU implementation.
1754 // We play it safe by always terminating the string explicitly.
1755 buf[len-1] = '\000';
1757 // If the function succeeded, we can use its exit code to determine the
1758 // semantics implemented by glibc
1762 // GNU semantics detected
1767 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
1768 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
1769 // This means an error on MacOSX or FreeBSD.
1773 strncat(buf, rc, len-1);
1779 LogMessageFatal::LogMessageFatal(const char* file, int line) :
1780 LogMessage(file, line, FATAL) {}
1782 LogMessageFatal::LogMessageFatal(const char* file, int line,
1783 const CheckOpString& result) :
1784 LogMessage(file, line, result) {}
1786 LogMessageFatal::~LogMessageFatal() {
1791 void InitGoogleLogging(const char* argv0) {
1792 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
1795 void ShutdownGoogleLogging() {
1796 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
1797 LogDestination::DeleteLogDestinations();
1798 delete logging_directories_list;
1799 logging_directories_list = NULL;
1802 _END_GOOGLE_NAMESPACE_