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"
39 # include <unistd.h> // For _exit.
42 #include <sys/types.h>
44 #ifdef HAVE_SYS_UTSNAME_H
45 # include <sys/utsname.h> // For uname.
59 #include <errno.h> // for errno
61 #include "base/commandlineflags.h" // to get the program name
62 #include "glog/logging.h"
63 #include "glog/raw_logging.h"
64 #include "base/googleinit.h"
66 #ifdef HAVE_STACKTRACE
67 # include "stacktrace.h"
78 using std::ostringstream;
91 // There is no thread annotation support.
92 #define EXCLUSIVE_LOCKS_REQUIRED(mu)
94 static bool BoolFromEnv(const char *varname, bool defval) {
95 const char* const valstr = getenv(varname);
99 return memchr("tTyY1\0", valstr[0], 6) != NULL;
102 GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
103 "log messages go to stderr instead of logfiles");
104 GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
105 "log messages go to stderr in addition to logfiles");
106 GLOG_DEFINE_bool(colorlogtostderr, false,
107 "color messages logged to stderr (if supported by terminal)");
109 GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
110 "Logs can grow very quickly and they are rarely read before they "
111 "need to be evicted from memory. Instead, drop them from memory "
112 "as soon as they are flushed to disk.");
113 _START_GOOGLE_NAMESPACE_
115 static const int64 kPageSize = getpagesize();
117 _END_GOOGLE_NAMESPACE_
120 // By default, errors (including fatal errors) get logged to stderr as
123 // The default is ERROR instead of FATAL so that users can see problems
124 // when they run a program without having to look in another file.
125 DEFINE_int32(stderrthreshold,
126 GOOGLE_NAMESPACE::GLOG_ERROR,
127 "log messages at or above this level are copied to stderr in "
128 "addition to logfiles. This flag obsoletes --alsologtostderr.");
130 GLOG_DEFINE_string(alsologtoemail, "",
131 "log messages go to these email addresses "
132 "in addition to logfiles");
133 GLOG_DEFINE_bool(log_prefix, true,
134 "Prepend the log prefix to the start of each log line");
135 GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
136 "actually get logged anywhere");
137 GLOG_DEFINE_int32(logbuflevel, 0,
138 "Buffer log messages logged at this level or lower"
139 " (-1 means don't buffer; 0 means buffer INFO only;"
141 GLOG_DEFINE_int32(logbufsecs, 30,
142 "Buffer log messages for at most this many seconds");
143 GLOG_DEFINE_int32(logemaillevel, 999,
144 "Email log messages logged at this level or higher"
145 " (0 means email all; 3 means email FATAL only;"
147 GLOG_DEFINE_string(logmailer, "/bin/mail",
148 "Mailer used to send logging email");
150 // Compute the default value for --log_dir
151 static const char* DefaultLogDir() {
153 env = getenv("GOOGLE_LOG_DIR");
154 if (env != NULL && env[0] != '\0') {
157 env = getenv("TEST_TMPDIR");
158 if (env != NULL && env[0] != '\0') {
164 GLOG_DEFINE_string(log_dir, DefaultLogDir(),
165 "If specified, logfiles are written into this directory instead "
166 "of the default logging directory.");
167 GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
168 "files in this directory");
170 GLOG_DEFINE_int32(max_log_size, 1800,
171 "approx. maximum log file size (in MB). A value of 0 will "
172 "be silently overridden to 1.");
174 GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
175 "Stop attempting to log to disk if the disk is full.");
177 GLOG_DEFINE_string(log_backtrace_at, "",
178 "Emit a backtrace when logging at file:linenum.");
180 // TODO(hamaji): consider windows
181 #define PATH_SEPARATOR '/'
184 #if defined(OS_WINDOWS)
186 #define ssize_t SSIZE_T
188 static ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
189 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
190 if (orig_offset == (off_t)-1)
192 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
194 ssize_t len = read(fd, buf, count);
197 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
201 #endif // !HAVE_PREAD
204 static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) {
205 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
206 if (orig_offset == (off_t)-1)
208 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
210 ssize_t len = write(fd, buf, count);
213 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
217 #endif // !HAVE_PWRITE
219 static void GetHostName(string* hostname) {
220 #if defined(HAVE_SYS_UTSNAME_H)
222 if (0 != uname(&buf)) {
223 // ensure null termination on failure
224 *buf.nodename = '\0';
226 *hostname = buf.nodename;
227 #elif defined(OS_WINDOWS)
228 char buf[MAX_COMPUTERNAME_LENGTH + 1];
229 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
230 if (GetComputerNameA(buf, &len)) {
236 # warning There is no way to retrieve the host name.
237 *hostname = "(unknown)";
241 // Returns true iff terminal supports using colors in output.
242 static bool TerminalSupportsColor() {
243 bool term_supports_color = false;
245 // on Windows TERM variable is usually not set, but the console does
247 term_supports_color = true;
249 // On non-Windows platforms, we rely on the TERM variable.
250 const char* const term = getenv("TERM");
251 if (term != NULL && term[0] != '\0') {
252 term_supports_color =
253 !strcmp(term, "xterm") ||
254 !strcmp(term, "xterm-color") ||
255 !strcmp(term, "xterm-256color") ||
256 !strcmp(term, "screen-256color") ||
257 !strcmp(term, "screen") ||
258 !strcmp(term, "linux") ||
259 !strcmp(term, "cygwin");
262 return term_supports_color;
265 _START_GOOGLE_NAMESPACE_
274 static GLogColor SeverityToColor(LogSeverity severity) {
275 assert(severity >= 0 && severity < NUM_SEVERITIES);
276 GLogColor color = COLOR_DEFAULT;
279 color = COLOR_DEFAULT;
282 color = COLOR_YELLOW;
289 // should never get here.
297 // Returns the character attribute for the given color.
298 WORD GetColorAttribute(GLogColor color) {
300 case COLOR_RED: return FOREGROUND_RED;
301 case COLOR_GREEN: return FOREGROUND_GREEN;
302 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
309 // Returns the ANSI color code for the given color.
310 const char* GetAnsiColorCode(GLogColor color) {
312 case COLOR_RED: return "1";
313 case COLOR_GREEN: return "2";
314 case COLOR_YELLOW: return "3";
315 case COLOR_DEFAULT: return "";
317 return NULL; // stop warning about return type.
322 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
323 static int32 MaxLogSize() {
324 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
327 // An arbitrary limit on the length of a single log message. This
328 // is so that streaming can be done more efficiently.
329 const size_t LogMessage::kMaxLogMessageLen = 30000;
331 struct LogMessage::LogMessageData {
334 int preserved_errno_; // preserved errno
335 // Buffer space; contains complete message text.
336 char message_text_[LogMessage::kMaxLogMessageLen+1];
338 char severity_; // What level is this LogMessage logged at?
339 int line_; // line number where logging call is.
340 void (LogMessage::*send_method_)(); // Call this in destructor to send
341 union { // At most one of these is used: union to keep the size low.
342 LogSink* sink_; // NULL or sink to send message to
343 std::vector<std::string>* outvec_; // NULL or vector to push message onto
344 std::string* message_; // NULL or string to write message into
346 time_t timestamp_; // Time of creation of LogMessage
347 struct ::tm tm_time_; // Time of creation of LogMessage
348 size_t num_prefix_chars_; // # of chars of prefix in this message
349 size_t num_chars_to_log_; // # of chars of msg to send to log
350 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
351 const char* basename_; // basename of file that called LOG
352 const char* fullname_; // fullname of file that called LOG
353 bool has_been_flushed_; // false => data has not been flushed
354 bool first_fatal_; // true => this was first fatal msg
357 LogMessageData(const LogMessageData&);
358 void operator=(const LogMessageData&);
361 // A mutex that allows only one thread to log at a time, to keep things from
362 // getting jumbled. Some other very uncommon logging operations (like
363 // changing the destination file for log messages of a given severity) also
364 // lock this mutex. Please be sure that anybody who might possibly need to
366 static Mutex log_mutex;
368 // Number of messages sent at each severity. Under log_mutex.
369 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
371 // Globally disable log writing (if disk is full)
372 static bool stop_writing = false;
374 const char*const LogSeverityNames[NUM_SEVERITIES] = {
375 "INFO", "WARNING", "ERROR", "FATAL"
378 // Has the user called SetExitOnDFatal(true)?
379 static bool exit_on_dfatal = true;
381 const char* GetLogSeverityName(LogSeverity severity) {
382 return LogSeverityNames[severity];
385 static bool SendEmailInternal(const char*dest, const char *subject,
386 const char*body, bool use_logging);
388 base::Logger::~Logger() {
393 // Encapsulates all file-system related state
394 class LogFileObject : public base::Logger {
396 LogFileObject(LogSeverity severity, const char* base_filename);
399 virtual void Write(bool force_flush, // Should we force a flush here?
400 time_t timestamp, // Timestamp for this entry
404 // Configuration options
405 void SetBasename(const char* basename);
406 void SetExtension(const char* ext);
407 void SetSymlinkBasename(const char* symlink_basename);
409 // Normal flushing routine
410 virtual void Flush();
412 // It is the actual file length for the system loggers,
413 // i.e., INFO, ERROR, etc.
414 virtual uint32 LogSize() {
419 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
420 // can avoid grabbing a lock. Usually Flush() calls it after
422 void FlushUnlocked();
425 static const uint32 kRolloverAttemptFrequency = 0x20;
428 bool base_filename_selected_;
429 string base_filename_;
430 string symlink_basename_;
431 string filename_extension_; // option users can specify (eg to add port#)
433 LogSeverity severity_;
434 uint32 bytes_since_flush_;
436 unsigned int rollover_attempt_;
437 int64 next_flush_time_; // cycle count at which to flush log
439 // Actually create a logfile using the value of base_filename_ and the
440 // supplied argument time_pid_string
441 // REQUIRES: lock_ is held
442 bool CreateLogfile(const string& time_pid_string);
447 class LogDestination {
449 friend class LogMessage;
450 friend void ReprintFatalMessage();
451 friend base::Logger* base::GetLogger(LogSeverity);
452 friend void base::SetLogger(LogSeverity, base::Logger*);
454 // These methods are just forwarded to by their global versions.
455 static void SetLogDestination(LogSeverity severity,
456 const char* base_filename);
457 static void SetLogSymlink(LogSeverity severity,
458 const char* symlink_basename);
459 static void AddLogSink(LogSink *destination);
460 static void RemoveLogSink(LogSink *destination);
461 static void SetLogFilenameExtension(const char* filename_extension);
462 static void SetStderrLogging(LogSeverity min_severity);
463 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
464 static void LogToStderr();
465 // Flush all log files that are at least at the given severity level
466 static void FlushLogFiles(int min_severity);
467 static void FlushLogFilesUnsafe(int min_severity);
469 // we set the maximum size of our packet to be 1400, the logic being
470 // to prevent fragmentation.
471 // Really this number is arbitrary.
472 static const int kNetworkBytes = 1400;
474 static const string& hostname();
475 static const bool& terminal_supports_color() {
476 return terminal_supports_color_;
479 static void DeleteLogDestinations();
482 LogDestination(LogSeverity severity, const char* base_filename);
483 ~LogDestination() { }
485 // Take a log message of a particular severity and log it to stderr
486 // iff it's of a high enough severity to deserve it.
487 static void MaybeLogToStderr(LogSeverity severity, const char* message,
490 // Take a log message of a particular severity and log it to email
491 // iff it's of a high enough severity to deserve it.
492 static void MaybeLogToEmail(LogSeverity severity, const char* message,
494 // Take a log message of a particular severity and log it to a file
495 // iff the base filename is not "" (which means "don't log to me")
496 static void MaybeLogToLogfile(LogSeverity severity,
498 const char* message, size_t len);
499 // Take a log message of a particular severity and log it to the file
500 // for that severity and also for all files with severity less than
502 static void LogToAllLogfiles(LogSeverity severity,
504 const char* message, size_t len);
506 // Send logging info to all registered sinks.
507 static void LogToSinks(LogSeverity severity,
508 const char *full_filename,
509 const char *base_filename,
511 const struct ::tm* tm_time,
515 // Wait for all registered sinks via WaitTillSent
516 // including the optional one in "data".
517 static void WaitForSinks(LogMessage::LogMessageData* data);
519 static LogDestination* log_destination(LogSeverity severity);
521 LogFileObject fileobject_;
522 base::Logger* logger_; // Either &fileobject_, or wrapper around it
524 static LogDestination* log_destinations_[NUM_SEVERITIES];
525 static LogSeverity email_logging_severity_;
526 static string addresses_;
527 static string hostname_;
528 static bool terminal_supports_color_;
530 // arbitrary global logging destinations.
531 static vector<LogSink*>* sinks_;
533 // Protects the vector sinks_,
534 // but not the LogSink objects its elements reference.
535 static Mutex sink_mutex_;
538 LogDestination(const LogDestination&);
539 LogDestination& operator=(const LogDestination&);
542 // Errors do not get logged to email by default.
543 LogSeverity LogDestination::email_logging_severity_ = 99999;
545 string LogDestination::addresses_;
546 string LogDestination::hostname_;
548 vector<LogSink*>* LogDestination::sinks_ = NULL;
549 Mutex LogDestination::sink_mutex_;
550 bool LogDestination::terminal_supports_color_ = TerminalSupportsColor();
553 const string& LogDestination::hostname() {
554 if (hostname_.empty()) {
555 GetHostName(&hostname_);
556 if (hostname_.empty()) {
557 hostname_ = "(unknown)";
563 LogDestination::LogDestination(LogSeverity severity,
564 const char* base_filename)
565 : fileobject_(severity, base_filename),
566 logger_(&fileobject_) {
569 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
570 // assume we have the log_mutex or we simply don't care
572 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
573 LogDestination* log = log_destination(i);
575 // Flush the base fileobject_ logger directly instead of going
576 // through any wrappers to reduce chance of deadlock.
577 log->fileobject_.FlushUnlocked();
582 inline void LogDestination::FlushLogFiles(int min_severity) {
583 // Prevent any subtle race conditions by wrapping a mutex lock around
585 MutexLock l(&log_mutex);
586 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
587 LogDestination* log = log_destination(i);
589 log->logger_->Flush();
594 inline void LogDestination::SetLogDestination(LogSeverity severity,
595 const char* base_filename) {
596 assert(severity >= 0 && severity < NUM_SEVERITIES);
597 // Prevent any subtle race conditions by wrapping a mutex lock around
599 MutexLock l(&log_mutex);
600 log_destination(severity)->fileobject_.SetBasename(base_filename);
603 inline void LogDestination::SetLogSymlink(LogSeverity severity,
604 const char* symlink_basename) {
605 CHECK_GE(severity, 0);
606 CHECK_LT(severity, NUM_SEVERITIES);
607 MutexLock l(&log_mutex);
608 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
611 inline void LogDestination::AddLogSink(LogSink *destination) {
612 // Prevent any subtle race conditions by wrapping a mutex lock around
614 MutexLock l(&sink_mutex_);
615 if (!sinks_) sinks_ = new vector<LogSink*>;
616 sinks_->push_back(destination);
619 inline void LogDestination::RemoveLogSink(LogSink *destination) {
620 // Prevent any subtle race conditions by wrapping a mutex lock around
622 MutexLock l(&sink_mutex_);
623 // This doesn't keep the sinks in order, but who cares?
625 for (int i = sinks_->size() - 1; i >= 0; i--) {
626 if ((*sinks_)[i] == destination) {
627 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
635 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
636 // Prevent any subtle race conditions by wrapping a mutex lock around
638 MutexLock l(&log_mutex);
639 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
640 log_destination(severity)->fileobject_.SetExtension(ext);
644 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
645 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
646 // Prevent any subtle race conditions by wrapping a mutex lock around
648 MutexLock l(&log_mutex);
649 FLAGS_stderrthreshold = min_severity;
652 inline void LogDestination::LogToStderr() {
653 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
654 // SetLogDestination already do the locking!
655 SetStderrLogging(0); // thus everything is "also" logged to stderr
656 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
657 SetLogDestination(i, ""); // "" turns off logging to a logfile
661 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
662 const char* addresses) {
663 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
664 // Prevent any subtle race conditions by wrapping a mutex lock around
666 MutexLock l(&log_mutex);
667 LogDestination::email_logging_severity_ = min_severity;
668 LogDestination::addresses_ = addresses;
671 static void ColoredWriteToStderr(LogSeverity severity,
672 const char* message, size_t len) {
673 const GLogColor color =
674 (LogDestination::terminal_supports_color() && FLAGS_colorlogtostderr) ?
675 SeverityToColor(severity) : COLOR_DEFAULT;
677 // Avoid using cerr from this module since we may get called during
678 // exit code, and cerr may be partially or fully destroyed by then.
679 if (COLOR_DEFAULT == color) {
680 fwrite(message, len, 1, stderr);
684 const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
686 // Gets the current text color.
687 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
688 GetConsoleScreenBufferInfo(stderr_handle, &buffer_info);
689 const WORD old_color_attrs = buffer_info.wAttributes;
691 // We need to flush the stream buffers into the console before each
692 // SetConsoleTextAttribute call lest it affect the text that is already
693 // printed but has not yet reached the console.
695 SetConsoleTextAttribute(stderr_handle,
696 GetColorAttribute(color) | FOREGROUND_INTENSITY);
697 fwrite(message, len, 1, stderr);
699 // Restores the text color.
700 SetConsoleTextAttribute(stderr_handle, old_color_attrs);
702 fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color));
703 fwrite(message, len, 1, stderr);
704 fprintf(stderr, "\033[m"); // Resets the terminal to default.
708 static void WriteToStderr(const char* message, size_t len) {
709 // Avoid using cerr from this module since we may get called during
710 // exit code, and cerr may be partially or fully destroyed by then.
711 fwrite(message, len, 1, stderr);
714 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
715 const char* message, size_t len) {
716 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
717 ColoredWriteToStderr(severity, message, len);
719 // On Windows, also output to the debugger
720 ::OutputDebugStringA(string(message,len).c_str());
726 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
727 const char* message, size_t len) {
728 if (severity >= email_logging_severity_ ||
729 severity >= FLAGS_logemaillevel) {
730 string to(FLAGS_alsologtoemail);
731 if (!addresses_.empty()) {
737 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
738 glog_internal_namespace_::ProgramInvocationShortName());
739 string body(hostname());
741 body.append(message, len);
743 // should NOT use SendEmail(). The caller of this function holds the
744 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
745 // acquire the log_mutex object. Use SendEmailInternal() and set
746 // use_logging to false.
747 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
752 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
756 const bool should_flush = severity > FLAGS_logbuflevel;
757 LogDestination* destination = log_destination(severity);
758 destination->logger_->Write(should_flush, timestamp, message, len);
761 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
766 if ( FLAGS_logtostderr ) { // global flag: never log to file
767 ColoredWriteToStderr(severity, message, len);
769 for (int i = severity; i >= 0; --i)
770 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
774 inline void LogDestination::LogToSinks(LogSeverity severity,
775 const char *full_filename,
776 const char *base_filename,
778 const struct ::tm* tm_time,
780 size_t message_len) {
781 ReaderMutexLock l(&sink_mutex_);
783 for (int i = sinks_->size() - 1; i >= 0; i--) {
784 (*sinks_)[i]->send(severity, full_filename, base_filename,
785 line, tm_time, message, message_len);
790 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
791 ReaderMutexLock l(&sink_mutex_);
793 for (int i = sinks_->size() - 1; i >= 0; i--) {
794 (*sinks_)[i]->WaitTillSent();
797 const bool send_to_sink =
798 (data->send_method_ == &LogMessage::SendToSink) ||
799 (data->send_method_ == &LogMessage::SendToSinkAndLog);
800 if (send_to_sink && data->sink_ != NULL) {
801 data->sink_->WaitTillSent();
805 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
807 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
808 assert(severity >=0 && severity < NUM_SEVERITIES);
809 if (!log_destinations_[severity]) {
810 log_destinations_[severity] = new LogDestination(severity, NULL);
812 return log_destinations_[severity];
815 void LogDestination::DeleteLogDestinations() {
816 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
817 delete log_destinations_[severity];
818 log_destinations_[severity] = NULL;
820 MutexLock l(&sink_mutex_);
826 LogFileObject::LogFileObject(LogSeverity severity,
827 const char* base_filename)
828 : base_filename_selected_(base_filename != NULL),
829 base_filename_((base_filename != NULL) ? base_filename : ""),
830 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
831 filename_extension_(),
834 bytes_since_flush_(0),
836 rollover_attempt_(kRolloverAttemptFrequency-1),
837 next_flush_time_(0) {
838 assert(severity >= 0);
839 assert(severity < NUM_SEVERITIES);
842 LogFileObject::~LogFileObject() {
850 void LogFileObject::SetBasename(const char* basename) {
852 base_filename_selected_ = true;
853 if (base_filename_ != basename) {
854 // Get rid of old log file since we are changing names
858 rollover_attempt_ = kRolloverAttemptFrequency-1;
860 base_filename_ = basename;
864 void LogFileObject::SetExtension(const char* ext) {
866 if (filename_extension_ != ext) {
867 // Get rid of old log file since we are changing names
871 rollover_attempt_ = kRolloverAttemptFrequency-1;
873 filename_extension_ = ext;
877 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
879 symlink_basename_ = symlink_basename;
882 void LogFileObject::Flush() {
887 void LogFileObject::FlushUnlocked(){
890 bytes_since_flush_ = 0;
892 // Figure out when we are due for another flush.
893 const int64 next = (FLAGS_logbufsecs
894 * static_cast<int64>(1000000)); // in usec
895 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
898 bool LogFileObject::CreateLogfile(const string& time_pid_string) {
899 string string_filename = base_filename_+filename_extension_+
901 const char* filename = string_filename.c_str();
902 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
903 if (fd == -1) return false;
905 // Mark the file close-on-exec. We don't really care if this fails
906 fcntl(fd, F_SETFD, FD_CLOEXEC);
909 file_ = fdopen(fd, "a"); // Make a FILE*.
910 if (file_ == NULL) { // Man, we're screwed!
912 unlink(filename); // Erase the half-baked evidence: an unusable log file
916 // We try to create a symlink called <program_name>.<severity>,
917 // which is easier to use. (Every time we create a new logfile,
918 // we destroy the old symlink and create a new one, so it always
919 // points to the latest logfile.) If it fails, we're sad but it's
921 if (!symlink_basename_.empty()) {
922 // take directory from filename
923 const char* slash = strrchr(filename, PATH_SEPARATOR);
924 const string linkname =
925 symlink_basename_ + '.' + LogSeverityNames[severity_];
927 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
928 linkpath += linkname;
929 unlink(linkpath.c_str()); // delete old one if it exists
931 #if defined(OS_WINDOWS)
932 // TODO(hamaji): Create lnk file on Windows?
933 #elif defined(HAVE_UNISTD_H)
934 // We must have unistd.h.
935 // Make the symlink be relative (in the same dir) so that if the
936 // entire log directory gets relocated the link is still valid.
937 const char *linkdest = slash ? (slash + 1) : filename;
938 if (symlink(linkdest, linkpath.c_str()) != 0) {
939 // silently ignore failures
942 // Make an additional link to the log file in a place specified by
943 // FLAGS_log_link, if indicated
944 if (!FLAGS_log_link.empty()) {
945 linkpath = FLAGS_log_link + "/" + linkname;
946 unlink(linkpath.c_str()); // delete old one if it exists
947 if (symlink(filename, linkpath.c_str()) != 0) {
948 // silently ignore failures
954 return true; // Everything worked
957 void LogFileObject::Write(bool force_flush,
963 // We don't log if the base_name_ is "" (which means "don't write")
964 if (base_filename_selected_ && base_filename_.empty()) {
968 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
970 if (file_ != NULL) fclose(file_);
972 file_length_ = bytes_since_flush_ = 0;
973 rollover_attempt_ = kRolloverAttemptFrequency-1;
976 // If there's no destination file, make one before outputting
978 // Try to rollover the log file every 32 log messages. The only time
979 // this could matter would be when we have trouble creating the log
980 // file. If that happens, we'll lose lots of log messages, of course!
981 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
982 rollover_attempt_ = 0;
985 localtime_r(×tamp, &tm_time);
987 // The logfile's filename will have the date/time & pid in it
988 ostringstream time_pid_stream;
989 time_pid_stream.fill('0');
990 time_pid_stream << 1900+tm_time.tm_year
991 << setw(2) << 1+tm_time.tm_mon
992 << setw(2) << tm_time.tm_mday
994 << setw(2) << tm_time.tm_hour
995 << setw(2) << tm_time.tm_min
996 << setw(2) << tm_time.tm_sec
998 << GetMainThreadPid();
999 const string& time_pid_string = time_pid_stream.str();
1001 if (base_filename_selected_) {
1002 if (!CreateLogfile(time_pid_string)) {
1003 perror("Could not create log file");
1004 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
1005 time_pid_string.c_str());
1009 // If no base filename for logs of this severity has been set, use a
1010 // default base filename of
1011 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
1012 // logfiles will have names like
1013 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
1014 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
1015 // and 4354 is the pid of the logging process. The date & time reflect
1016 // when the file was created for output.
1018 // Where does the file get put? Successively try the directories
1020 string stripped_filename(
1021 glog_internal_namespace_::ProgramInvocationShortName());
1023 GetHostName(&hostname);
1025 string uidname = MyUserName();
1026 // We should not call CHECK() here because this function can be
1027 // called after holding on to log_mutex. We don't want to
1028 // attempt to hold on to the same mutex, and get into a
1029 // deadlock. Simply use a name like invalid-user.
1030 if (uidname.empty()) uidname = "invalid-user";
1032 stripped_filename = stripped_filename+'.'+hostname+'.'
1034 +LogSeverityNames[severity_]+'.';
1035 // We're going to (potentially) try to put logs in several different dirs
1036 const vector<string> & log_dirs = GetLoggingDirectories();
1038 // Go through the list of dirs, and try to create the log file in each
1039 // until we succeed or run out of options
1040 bool success = false;
1041 for (vector<string>::const_iterator dir = log_dirs.begin();
1042 dir != log_dirs.end();
1044 base_filename_ = *dir + "/" + stripped_filename;
1045 if ( CreateLogfile(time_pid_string) ) {
1050 // If we never succeeded, we have to give up
1051 if ( success == false ) {
1052 perror("Could not create logging file");
1053 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
1054 time_pid_string.c_str());
1059 // Write a header message into the log file
1060 ostringstream file_header_stream;
1061 file_header_stream.fill('0');
1062 file_header_stream << "Log file created at: "
1063 << 1900+tm_time.tm_year << '/'
1064 << setw(2) << 1+tm_time.tm_mon << '/'
1065 << setw(2) << tm_time.tm_mday
1067 << setw(2) << tm_time.tm_hour << ':'
1068 << setw(2) << tm_time.tm_min << ':'
1069 << setw(2) << tm_time.tm_sec << '\n'
1070 << "Running on machine: "
1071 << LogDestination::hostname() << '\n'
1072 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
1073 << "threadid file:line] msg" << '\n';
1074 const string& file_header_string = file_header_stream.str();
1076 const int header_len = file_header_string.size();
1077 fwrite(file_header_string.data(), 1, header_len, file_);
1078 file_length_ += header_len;
1079 bytes_since_flush_ += header_len;
1082 // Write to LOG file
1083 if ( !stop_writing ) {
1084 // fwrite() doesn't return an error when the disk is full, for
1085 // messages that are less than 4096 bytes. When the disk is full,
1086 // it returns the message length for messages that are less than
1087 // 4096 bytes. fwrite() returns 4096 for message lengths that are
1088 // greater than 4096, thereby indicating an error.
1090 fwrite(message, 1, message_len, file_);
1091 if ( FLAGS_stop_logging_if_full_disk &&
1092 errno == ENOSPC ) { // disk full, stop writing to disk
1093 stop_writing = true; // until the disk is
1096 file_length_ += message_len;
1097 bytes_since_flush_ += message_len;
1100 if ( CycleClock_Now() >= next_flush_time_ )
1101 stop_writing = false; // check to see if disk has free space.
1102 return; // no need to flush
1105 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
1106 // or every "FLAGS_logbufsecs" seconds.
1108 (bytes_since_flush_ >= 1000000) ||
1109 (CycleClock_Now() >= next_flush_time_) ) {
1112 if (FLAGS_drop_log_memory) {
1113 if (file_length_ >= logging::kPageSize) {
1114 // don't evict the most recent page
1115 uint32 len = file_length_ & ~(logging::kPageSize - 1);
1116 posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
1126 // Static log data space to avoid alloc failures in a LOG(FATAL)
1128 // Since multiple threads may call LOG(FATAL), and we want to preserve
1129 // the data from the first call, we allocate two sets of space. One
1130 // for exclusive use by the first thread, and one for shared use by
1131 // all other threads.
1132 static Mutex fatal_msg_lock;
1133 static CrashReason crash_reason;
1134 static bool fatal_msg_exclusive = true;
1135 static LogMessage::LogMessageData fatal_msg_data_exclusive;
1136 static LogMessage::LogMessageData fatal_msg_data_shared;
1138 LogMessage::LogMessageData::LogMessageData()
1139 : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) {
1142 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1143 int ctr, void (LogMessage::*send_method)())
1144 : allocated_(NULL) {
1145 Init(file, line, severity, send_method);
1146 data_->stream_.set_ctr(ctr);
1149 LogMessage::LogMessage(const char* file, int line,
1150 const CheckOpString& result)
1151 : allocated_(NULL) {
1152 Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
1153 stream() << "Check failed: " << (*result.str_) << " ";
1156 LogMessage::LogMessage(const char* file, int line)
1157 : allocated_(NULL) {
1158 Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
1161 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
1162 : allocated_(NULL) {
1163 Init(file, line, severity, &LogMessage::SendToLog);
1166 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1167 LogSink* sink, bool also_send_to_log)
1168 : allocated_(NULL) {
1169 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
1170 &LogMessage::SendToSink);
1171 data_->sink_ = sink; // override Init()'s setting to NULL
1174 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1175 vector<string> *outvec)
1176 : allocated_(NULL) {
1177 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
1178 data_->outvec_ = outvec; // override Init()'s setting to NULL
1181 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1183 : allocated_(NULL) {
1184 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
1185 data_->message_ = message; // override Init()'s setting to NULL
1188 void LogMessage::Init(const char* file,
1190 LogSeverity severity,
1191 void (LogMessage::*send_method)()) {
1193 if (severity != GLOG_FATAL || !exit_on_dfatal) {
1194 allocated_ = new LogMessageData();
1196 data_->first_fatal_ = false;
1198 MutexLock l(&fatal_msg_lock);
1199 if (fatal_msg_exclusive) {
1200 fatal_msg_exclusive = false;
1201 data_ = &fatal_msg_data_exclusive;
1202 data_->first_fatal_ = true;
1204 data_ = &fatal_msg_data_shared;
1205 data_->first_fatal_ = false;
1210 data_->preserved_errno_ = errno;
1211 data_->severity_ = severity;
1212 data_->line_ = line;
1213 data_->send_method_ = send_method;
1214 data_->sink_ = NULL;
1215 data_->outvec_ = NULL;
1216 WallTime now = WallTime_Now();
1217 data_->timestamp_ = static_cast<time_t>(now);
1218 localtime_r(&data_->timestamp_, &data_->tm_time_);
1219 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1220 RawLog__SetLastTime(data_->tm_time_, usecs);
1222 data_->num_chars_to_log_ = 0;
1223 data_->num_chars_to_syslog_ = 0;
1224 data_->basename_ = const_basename(file);
1225 data_->fullname_ = file;
1226 data_->has_been_flushed_ = false;
1228 // If specified, prepend a prefix to each line. For example:
1229 // I1018 160715 f5d4fbb0 logging.cc:1153]
1230 // (log level, GMT month, date, time, thread_id, file basename, line)
1231 // We exclude the thread_id for the default thread.
1232 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1233 stream() << LogSeverityNames[severity][0]
1234 << setw(2) << 1+data_->tm_time_.tm_mon
1235 << setw(2) << data_->tm_time_.tm_mday
1237 << setw(2) << data_->tm_time_.tm_hour << ':'
1238 << setw(2) << data_->tm_time_.tm_min << ':'
1239 << setw(2) << data_->tm_time_.tm_sec << "."
1242 << setfill(' ') << setw(5)
1243 << static_cast<unsigned int>(GetTID()) << setfill('0')
1245 << data_->basename_ << ':' << data_->line_ << "] ";
1247 data_->num_prefix_chars_ = data_->stream_.pcount();
1249 if (!FLAGS_log_backtrace_at.empty()) {
1251 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1252 #ifdef HAVE_STACKTRACE
1253 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1255 DumpStackTraceToString(&stacktrace);
1256 stream() << " (stacktrace:\n" << stacktrace << ") ";
1262 LogMessage::~LogMessage() {
1267 int LogMessage::preserved_errno() const {
1268 return data_->preserved_errno_;
1271 ostream& LogMessage::stream() {
1272 return data_->stream_;
1275 // Flush buffered message, called by the destructor, or any other function
1276 // that needs to synchronize the log.
1277 void LogMessage::Flush() {
1278 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1281 data_->num_chars_to_log_ = data_->stream_.pcount();
1282 data_->num_chars_to_syslog_ =
1283 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1285 // Do we need to add a \n to the end of this message?
1286 bool append_newline =
1287 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1288 char original_final_char = '\0';
1290 // If we do need to add a \n, we'll do it by violating the memory of the
1291 // ostrstream buffer. This is quick, and we'll make sure to undo our
1292 // modification before anything else is done with the ostrstream. It
1293 // would be preferable not to do things this way, but it seems to be
1294 // the best way to deal with this.
1295 if (append_newline) {
1296 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1297 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1300 // Prevent any subtle race conditions by wrapping a mutex lock around
1301 // the actual logging action per se.
1303 MutexLock l(&log_mutex);
1304 (this->*(data_->send_method_))();
1305 ++num_messages_[static_cast<int>(data_->severity_)];
1307 LogDestination::WaitForSinks(data_);
1309 if (append_newline) {
1310 // Fix the ostrstream back how it was before we screwed with it.
1311 // It's 99.44% certain that we don't need to worry about doing this.
1312 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1315 // If errno was already set before we enter the logging call, we'll
1316 // set it back to that value when we return from the logging call.
1317 // It happens often that we log an error message after a syscall
1318 // failure, which can potentially set the errno to some other
1319 // values. We would like to preserve the original errno.
1320 if (data_->preserved_errno_ != 0) {
1321 errno = data_->preserved_errno_;
1324 // Note that this message is now safely logged. If we're asked to flush
1325 // again, as a result of destruction, say, we'll do nothing on future calls.
1326 data_->has_been_flushed_ = true;
1329 // Copy of first FATAL log message so that we can print it out again
1330 // after all the stack traces. To preserve legacy behavior, we don't
1331 // use fatal_msg_data_exclusive.
1332 static time_t fatal_time;
1333 static char fatal_message[256];
1335 void ReprintFatalMessage() {
1336 if (fatal_message[0]) {
1337 const int n = strlen(fatal_message);
1338 if (!FLAGS_logtostderr) {
1339 // Also write to stderr (don't color to avoid terminal checks)
1340 WriteToStderr(fatal_message, n);
1342 LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1346 // L >= log_mutex (callers must hold the log_mutex).
1347 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1348 static bool already_warned_before_initgoogle = false;
1350 log_mutex.AssertHeld();
1352 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1353 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1355 // Messages of a given severity get logged to lower severity logs, too
1357 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1358 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1359 "written to STDERR\n";
1360 WriteToStderr(w, strlen(w));
1361 already_warned_before_initgoogle = true;
1364 // global flag: never log to file if set. Also -- don't log to a
1365 // file if we haven't parsed the command line flags to get the
1367 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1368 ColoredWriteToStderr(data_->severity_,
1369 data_->message_text_, data_->num_chars_to_log_);
1371 // this could be protected by a flag if necessary.
1372 LogDestination::LogToSinks(data_->severity_,
1373 data_->fullname_, data_->basename_,
1374 data_->line_, &data_->tm_time_,
1375 data_->message_text_ + data_->num_prefix_chars_,
1376 (data_->num_chars_to_log_ -
1377 data_->num_prefix_chars_ - 1));
1380 // log this message to all log files of severity <= severity_
1381 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1382 data_->message_text_,
1383 data_->num_chars_to_log_);
1385 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1386 data_->num_chars_to_log_);
1387 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1388 data_->num_chars_to_log_);
1389 LogDestination::LogToSinks(data_->severity_,
1390 data_->fullname_, data_->basename_,
1391 data_->line_, &data_->tm_time_,
1392 data_->message_text_ + data_->num_prefix_chars_,
1393 (data_->num_chars_to_log_
1394 - data_->num_prefix_chars_ - 1));
1395 // NOTE: -1 removes trailing \n
1398 // If we log a FATAL message, flush all the log destinations, then toss
1399 // a signal for others to catch. We leave the logs in a state that
1400 // someone else can use them (as long as they flush afterwards)
1401 if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1402 if (data_->first_fatal_) {
1403 // Store crash information so that it is accessible from within signal
1404 // handlers that may be invoked later.
1405 RecordCrashReason(&crash_reason);
1406 SetCrashReason(&crash_reason);
1408 // Store shortened fatal message for other logs and GWQ status
1409 const int copy = min<int>(data_->num_chars_to_log_,
1410 sizeof(fatal_message)-1);
1411 memcpy(fatal_message, data_->message_text_, copy);
1412 fatal_message[copy] = '\0';
1413 fatal_time = data_->timestamp_;
1416 if (!FLAGS_logtostderr) {
1417 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1418 if ( LogDestination::log_destinations_[i] )
1419 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1423 // release the lock that our caller (directly or indirectly)
1424 // LogMessage::~LogMessage() grabbed so that signal handlers
1425 // can use the logging facility. Alternately, we could add
1426 // an entire unsafe logging interface to bypass locking
1427 // for signal handlers but this seems simpler.
1429 LogDestination::WaitForSinks(data_);
1431 const char* message = "*** Check failure stack trace: ***\n";
1432 if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1439 void LogMessage::RecordCrashReason(
1440 glog_internal_namespace_::CrashReason* reason) {
1441 reason->filename = fatal_msg_data_exclusive.fullname_;
1442 reason->line_number = fatal_msg_data_exclusive.line_;
1443 reason->message = fatal_msg_data_exclusive.message_text_ +
1444 fatal_msg_data_exclusive.num_prefix_chars_;
1445 #ifdef HAVE_STACKTRACE
1446 // Retrieve the stack trace, omitting the logging frames that got us here.
1447 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1453 #ifdef HAVE___ATTRIBUTE__
1454 # define ATTRIBUTE_NORETURN __attribute__((noreturn))
1456 # define ATTRIBUTE_NORETURN
1459 static void logging_fail() ATTRIBUTE_NORETURN;
1461 static void logging_fail() {
1462 #if defined(_DEBUG) && defined(_MSC_VER)
1463 // When debugging on windows, avoid the obnoxious dialog and make
1464 // it possible to continue past a LOG(FATAL) in the debugger
1471 typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN;
1473 GOOGLE_GLOG_DLL_DECL
1474 logging_fail_func_t g_logging_fail_func = &logging_fail;
1476 void InstallFailureFunction(void (*fail_func)()) {
1477 g_logging_fail_func = (logging_fail_func_t)fail_func;
1480 void LogMessage::Fail() {
1481 g_logging_fail_func();
1484 // L >= log_mutex (callers must hold the log_mutex).
1485 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1486 if (data_->sink_ != NULL) {
1487 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1488 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1489 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1490 data_->line_, &data_->tm_time_,
1491 data_->message_text_ + data_->num_prefix_chars_,
1492 (data_->num_chars_to_log_ -
1493 data_->num_prefix_chars_ - 1));
1497 // L >= log_mutex (callers must hold the log_mutex).
1498 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1503 // L >= log_mutex (callers must hold the log_mutex).
1504 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1505 if (data_->outvec_ != NULL) {
1506 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1507 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1508 // Omit prefix of message and trailing newline when recording in outvec_.
1509 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1510 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1511 data_->outvec_->push_back(string(start, len));
1517 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1518 if (data_->message_ != NULL) {
1519 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1520 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1521 // Omit prefix of message and trailing newline when writing to message_.
1522 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1523 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1524 data_->message_->assign(start, len);
1529 // L >= log_mutex (callers must hold the log_mutex).
1530 void LogMessage::SendToSyslogAndLog() {
1531 #ifdef HAVE_SYSLOG_H
1532 // Before any calls to syslog(), make a single call to openlog()
1533 static bool openlog_already_called = false;
1534 if (!openlog_already_called) {
1535 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1536 LOG_CONS | LOG_NDELAY | LOG_PID,
1538 openlog_already_called = true;
1541 // This array maps Google severity levels to syslog levels
1542 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1543 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1544 int(data_->num_chars_to_syslog_),
1545 data_->message_text_ + data_->num_prefix_chars_);
1548 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1552 base::Logger* base::GetLogger(LogSeverity severity) {
1553 MutexLock l(&log_mutex);
1554 return LogDestination::log_destination(severity)->logger_;
1557 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1558 MutexLock l(&log_mutex);
1559 LogDestination::log_destination(severity)->logger_ = logger;
1562 // L < log_mutex. Acquires and releases mutex_.
1563 int64 LogMessage::num_messages(int severity) {
1564 MutexLock l(&log_mutex);
1565 return num_messages_[severity];
1568 // Output the COUNTER value. This is only valid if ostream is a
1570 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1572 LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
1574 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1576 CHECK(log && log == log->self())
1577 << "You must not use COUNTER with non-glog ostream";
1582 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1583 LogSeverity severity, int ctr,
1584 void (LogMessage::*send_method)())
1585 : LogMessage(file, line, severity, ctr, send_method) {
1588 ErrnoLogMessage::~ErrnoLogMessage() {
1589 // Don't access errno directly because it may have been altered
1590 // while streaming the message.
1591 stream() << ": " << StrError(preserved_errno()) << " ["
1592 << preserved_errno() << "]";
1595 void FlushLogFiles(LogSeverity min_severity) {
1596 LogDestination::FlushLogFiles(min_severity);
1599 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1600 LogDestination::FlushLogFilesUnsafe(min_severity);
1603 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1604 LogDestination::SetLogDestination(severity, base_filename);
1607 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1608 LogDestination::SetLogSymlink(severity, symlink_basename);
1611 LogSink::~LogSink() {
1614 void LogSink::WaitTillSent() {
1618 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1619 const struct ::tm* tm_time,
1620 const char* message, size_t message_len) {
1621 ostringstream stream(string(message, message_len));
1624 // FIXME(jrvb): Updating this to use the correct value for usecs
1625 // requires changing the signature for both this method and
1626 // LogSink::send(). This change needs to be done in a separate CL
1627 // so subclasses of LogSink can be updated at the same time.
1630 stream << LogSeverityNames[severity][0]
1631 << setw(2) << 1+tm_time->tm_mon
1632 << setw(2) << tm_time->tm_mday
1634 << setw(2) << tm_time->tm_hour << ':'
1635 << setw(2) << tm_time->tm_min << ':'
1636 << setw(2) << tm_time->tm_sec << '.'
1639 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1641 << file << ':' << line << "] ";
1643 stream << string(message, message_len);
1644 return stream.str();
1647 void AddLogSink(LogSink *destination) {
1648 LogDestination::AddLogSink(destination);
1651 void RemoveLogSink(LogSink *destination) {
1652 LogDestination::RemoveLogSink(destination);
1655 void SetLogFilenameExtension(const char* ext) {
1656 LogDestination::SetLogFilenameExtension(ext);
1659 void SetStderrLogging(LogSeverity min_severity) {
1660 LogDestination::SetStderrLogging(min_severity);
1663 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1664 LogDestination::SetEmailLogging(min_severity, addresses);
1667 void LogToStderr() {
1668 LogDestination::LogToStderr();
1672 namespace internal {
1674 bool GetExitOnDFatal() {
1675 MutexLock l(&log_mutex);
1676 return exit_on_dfatal;
1679 // Determines whether we exit the program for a LOG(DFATAL) message in
1680 // debug mode. It does this by skipping the call to Fail/FailQuietly.
1681 // This is intended for testing only.
1683 // This can have some effects on LOG(FATAL) as well. Failure messages
1684 // are always allocated (rather than sharing a buffer), the crash
1685 // reason is not recorded, the "gwq" status message is not updated,
1686 // and the stack trace is not recorded. The LOG(FATAL) *will* still
1687 // exit the program. Since this function is used only in testing,
1688 // these differences are acceptable.
1689 void SetExitOnDFatal(bool value) {
1690 MutexLock l(&log_mutex);
1691 exit_on_dfatal = value;
1694 } // namespace internal
1697 // use_logging controls whether the logging functions LOG/VLOG are used
1698 // to log errors. It should be set to false when the caller holds the
1700 static bool SendEmailInternal(const char*dest, const char *subject,
1701 const char*body, bool use_logging) {
1702 if (dest && *dest) {
1703 if ( use_logging ) {
1704 VLOG(1) << "Trying to send TITLE:" << subject
1705 << " BODY:" << body << " to " << dest;
1707 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1708 subject, body, dest);
1712 FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1713 FILE* pipe = popen(cmd.c_str(), "w");
1715 // Add the body if we have one
1717 fwrite(body, sizeof(char), strlen(body), pipe);
1718 bool ok = pclose(pipe) != -1;
1720 if ( use_logging ) {
1721 LOG(ERROR) << "Problems sending mail to " << dest << ": "
1724 fprintf(stderr, "Problems sending mail to %s: %s\n",
1725 dest, StrError(errno).c_str());
1730 if ( use_logging ) {
1731 LOG(ERROR) << "Unable to send mail to " << dest;
1733 fprintf(stderr, "Unable to send mail to %s\n", dest);
1740 bool SendEmail(const char*dest, const char *subject, const char*body){
1741 return SendEmailInternal(dest, subject, body, true);
1744 static void GetTempDirectories(vector<string>* list) {
1747 // On windows we'll try to find a directory in this order:
1748 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1751 // C:/WINDOWS/ or C:/WINNT/
1754 if (GetTempPathA(MAX_PATH, tmp))
1755 list->push_back(tmp);
1756 list->push_back("C:\\tmp\\");
1757 list->push_back("C:\\temp\\");
1759 // Directories, in order of preference. If we find a dir that
1760 // exists, we stop adding other less-preferred dirs
1761 const char * candidates[] = {
1762 // Non-null only during unittest/regtest
1763 getenv("TEST_TMPDIR"),
1765 // Explicitly-supplied temp dirs
1766 getenv("TMPDIR"), getenv("TMP"),
1768 // If all else fails
1772 for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
1773 const char *d = candidates[i];
1774 if (!d) continue; // Empty env var
1776 // Make sure we don't surprise anyone who's expecting a '/'
1778 if (dstr[dstr.size() - 1] != '/') {
1781 list->push_back(dstr);
1783 struct stat statbuf;
1784 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1785 // We found a dir that exists - we're done.
1793 static vector<string>* logging_directories_list;
1795 const vector<string>& GetLoggingDirectories() {
1796 // Not strictly thread-safe but we're called early in InitGoogle().
1797 if (logging_directories_list == NULL) {
1798 logging_directories_list = new vector<string>;
1800 if ( !FLAGS_log_dir.empty() ) {
1801 // A dir was specified, we should use it
1802 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1804 GetTempDirectories(logging_directories_list);
1807 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1808 logging_directories_list->push_back(tmp);
1809 logging_directories_list->push_back(".\\");
1811 logging_directories_list->push_back("./");
1815 return *logging_directories_list;
1818 void TestOnly_ClearLoggingDirectoriesList() {
1819 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1820 "called from test code.\n");
1821 delete logging_directories_list;
1822 logging_directories_list = NULL;
1825 void GetExistingTempDirectories(vector<string>* list) {
1826 GetTempDirectories(list);
1827 vector<string>::iterator i_dir = list->begin();
1828 while( i_dir != list->end() ) {
1829 // zero arg to access means test for existence; no constant
1830 // defined on windows
1831 if ( access(i_dir->c_str(), 0) ) {
1832 i_dir = list->erase(i_dir);
1839 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1840 #ifdef HAVE_UNISTD_H
1841 struct stat statbuf;
1842 const int kCopyBlockSize = 8 << 10;
1843 char copybuf[kCopyBlockSize];
1844 int64 read_offset, write_offset;
1845 // Don't follow symlinks unless they're our own fd symlinks in /proc
1847 // TODO(hamaji): Support other environments.
1849 const char *procfd_prefix = "/proc/self/fd/";
1850 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1853 int fd = open(path, flags);
1855 if (errno == EFBIG) {
1856 // The log file in question has got too big for us to open. The
1857 // real fix for this would be to compile logging.cc (or probably
1858 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1860 // Instead just truncate the file to something we can manage
1861 if (truncate(path, 0) == -1) {
1862 PLOG(ERROR) << "Unable to truncate " << path;
1864 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1867 PLOG(ERROR) << "Unable to open " << path;
1872 if (fstat(fd, &statbuf) == -1) {
1873 PLOG(ERROR) << "Unable to fstat()";
1877 // See if the path refers to a regular file bigger than the
1879 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1880 if (statbuf.st_size <= limit) goto out_close_fd;
1881 if (statbuf.st_size <= keep) goto out_close_fd;
1883 // This log file is too large - we need to truncate it
1884 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1886 // Copy the last "keep" bytes of the file to the beginning of the file
1887 read_offset = statbuf.st_size - keep;
1889 int bytesin, bytesout;
1890 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1891 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1892 if (bytesout == -1) {
1893 PLOG(ERROR) << "Unable to write to " << path;
1895 } else if (bytesout != bytesin) {
1896 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1898 read_offset += bytesin;
1899 write_offset += bytesout;
1901 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1903 // Truncate the remainder of the file. If someone else writes to the
1904 // end of the file after our last read() above, we lose their latest
1905 // data. Too bad ...
1906 if (ftruncate(fd, write_offset) == -1) {
1907 PLOG(ERROR) << "Unable to truncate " << path;
1913 LOG(ERROR) << "No log truncation support.";
1917 void TruncateStdoutStderr() {
1918 #ifdef HAVE_UNISTD_H
1919 int64 limit = MaxLogSize() << 20;
1920 int64 keep = 1 << 20;
1921 TruncateLogFile("/proc/self/fd/1", limit, keep);
1922 TruncateLogFile("/proc/self/fd/2", limit, keep);
1924 LOG(ERROR) << "No log truncation support.";
1929 // Helper functions for string comparisons.
1930 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1931 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1932 const char* names) { \
1933 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1934 if (equal == expected) return NULL; \
1939 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1940 return new string(ss.str()); \
1943 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1944 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1945 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1946 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1947 #undef DEFINE_CHECK_STROP_IMPL
1949 int posix_strerror_r(int err, char *buf, size_t len) {
1950 // Sanity check input parameters
1951 if (buf == NULL || len <= 0) {
1956 // Reset buf and errno, and try calling whatever version of strerror_r()
1957 // is implemented by glibc
1959 int old_errno = errno;
1961 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1963 // Both versions set errno on failure
1965 // Should already be there, but better safe than sorry
1971 // POSIX is vague about whether the string will be terminated, although
1972 // is indirectly implies that typically ERANGE will be returned, instead
1973 // of truncating the string. This is different from the GNU implementation.
1974 // We play it safe by always terminating the string explicitly.
1975 buf[len-1] = '\000';
1977 // If the function succeeded, we can use its exit code to determine the
1978 // semantics implemented by glibc
1982 // GNU semantics detected
1987 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
1988 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
1989 // This means an error on MacOSX or FreeBSD.
1993 strncat(buf, rc, len-1);
1999 string StrError(int err) {
2001 int rc = posix_strerror_r(err, buf, sizeof(buf));
2002 if ((rc < 0) || (buf[0] == '\000')) {
2003 snprintf(buf, sizeof(buf), "Error number %d", err);
2008 LogMessageFatal::LogMessageFatal(const char* file, int line) :
2009 LogMessage(file, line, GLOG_FATAL) {}
2011 LogMessageFatal::LogMessageFatal(const char* file, int line,
2012 const CheckOpString& result) :
2013 LogMessage(file, line, result) {}
2015 LogMessageFatal::~LogMessageFatal() {
2022 CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
2023 : stream_(new ostringstream) {
2024 *stream_ << exprtext << " (";
2027 CheckOpMessageBuilder::~CheckOpMessageBuilder() {
2031 ostream* CheckOpMessageBuilder::ForVar2() {
2032 *stream_ << " vs. ";
2036 string* CheckOpMessageBuilder::NewString() {
2038 return new string(stream_->str());
2044 void MakeCheckOpValueString(std::ostream* os, const char& v) {
2045 if (v >= 32 && v <= 126) {
2046 (*os) << "'" << v << "'";
2048 (*os) << "char value " << (short)v;
2053 void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
2054 if (v >= 32 && v <= 126) {
2055 (*os) << "'" << v << "'";
2057 (*os) << "signed char value " << (short)v;
2062 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
2063 if (v >= 32 && v <= 126) {
2064 (*os) << "'" << v << "'";
2066 (*os) << "unsigned char value " << (unsigned short)v;
2070 void InitGoogleLogging(const char* argv0) {
2071 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
2074 void ShutdownGoogleLogging() {
2075 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
2076 LogDestination::DeleteLogDestinations();
2077 delete logging_directories_list;
2078 logging_directories_list = NULL;
2081 _END_GOOGLE_NAMESPACE_