1 // Copyright (c) 1999, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite()
32 #include "utilities.h"
38 # include <unistd.h> // For _exit.
41 #include <sys/types.h>
43 #ifdef HAVE_SYS_UTSNAME_H
44 # include <sys/utsname.h> // For uname.
58 #include <errno.h> // for errno
60 #include "base/commandlineflags.h" // to get the program name
61 #include "glog/logging.h"
62 #include "glog/raw_logging.h"
63 #include "base/googleinit.h"
65 #ifdef HAVE_STACKTRACE
66 # include "stacktrace.h"
77 using std::ostringstream;
90 // There is no thread annotation support.
91 #define EXCLUSIVE_LOCKS_REQUIRED(mu)
93 static bool BoolFromEnv(const char *varname, bool defval) {
94 const char* const valstr = getenv(varname);
98 return memchr("tTyY1\0", valstr[0], 6) != NULL;
101 GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
102 "log messages go to stderr instead of logfiles");
103 GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
104 "log messages go to stderr in addition to logfiles");
105 GLOG_DEFINE_bool(colorstderr, false,
106 "color messages logged to stderr (if supported by terminal)");
108 GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
109 "Logs can grow very quickly and they are rarely read before they "
110 "need to be evicted from memory. Instead, drop them from memory "
111 "as soon as they are flushed to disk.");
112 _START_GOOGLE_NAMESPACE_
114 static const int64 kPageSize = getpagesize();
116 _END_GOOGLE_NAMESPACE_
119 // By default, errors (including fatal errors) get logged to stderr as
122 // The default is ERROR instead of FATAL so that users can see problems
123 // when they run a program without having to look in another file.
124 DEFINE_int32(stderrthreshold,
125 GOOGLE_NAMESPACE::GLOG_ERROR,
126 "log messages at or above this level are copied to stderr in "
127 "addition to logfiles. This flag obsoletes --alsologtostderr.");
129 GLOG_DEFINE_string(alsologtoemail, "",
130 "log messages go to these email addresses "
131 "in addition to logfiles");
132 GLOG_DEFINE_bool(log_prefix, true,
133 "Prepend the log prefix to the start of each log line");
134 GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
135 "actually get logged anywhere");
136 GLOG_DEFINE_int32(logbuflevel, 0,
137 "Buffer log messages logged at this level or lower"
138 " (-1 means don't buffer; 0 means buffer INFO only;"
140 GLOG_DEFINE_int32(logbufsecs, 30,
141 "Buffer log messages for at most this many seconds");
142 GLOG_DEFINE_int32(logemaillevel, 999,
143 "Email log messages logged at this level or higher"
144 " (0 means email all; 3 means email FATAL only;"
146 GLOG_DEFINE_string(logmailer, "/bin/mail",
147 "Mailer used to send logging email");
149 // Compute the default value for --log_dir
150 static const char* DefaultLogDir() {
152 env = getenv("GOOGLE_LOG_DIR");
153 if (env != NULL && env[0] != '\0') {
156 env = getenv("TEST_TMPDIR");
157 if (env != NULL && env[0] != '\0') {
163 GLOG_DEFINE_string(log_dir, DefaultLogDir(),
164 "If specified, logfiles are written into this directory instead "
165 "of the default logging directory.");
166 GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
167 "files in this directory");
169 GLOG_DEFINE_int32(max_log_size, 1800,
170 "approx. maximum log file size (in MB). A value of 0 will "
171 "be silently overridden to 1.");
173 GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
174 "Stop attempting to log to disk if the disk is full.");
176 GLOG_DEFINE_string(log_backtrace_at, "",
177 "Emit a backtrace when logging at file:linenum.");
179 // TODO(hamaji): consider windows
180 #define PATH_SEPARATOR '/'
182 static void GetHostName(string* hostname) {
183 #if defined(HAVE_SYS_UTSNAME_H)
185 if (0 != uname(&buf)) {
186 // ensure null termination on failure
187 *buf.nodename = '\0';
189 *hostname = buf.nodename;
190 #elif defined(OS_WINDOWS)
191 char buf[MAX_COMPUTERNAME_LENGTH + 1];
192 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
193 if (GetComputerNameA(buf, &len)) {
199 # warning There is no way to retrieve the host name.
200 *hostname = "(unknown)";
204 // Returns true iff terminal supports using colors in output.
205 static bool TerminalSupportsColor() {
206 bool term_supports_color = false;
208 // on Windows TERM variable is usually not set, but the console does
210 term_supports_color = true;
212 // On non-Windows platforms, we rely on the TERM variable.
213 const char* const term = getenv("TERM");
214 if (term != NULL && term[0] != '\0') {
215 term_supports_color =
216 !strcmp(term, "xterm") ||
217 !strcmp(term, "xterm-color") ||
218 !strcmp(term, "xterm-256color") ||
219 !strcmp(term, "screen") ||
220 !strcmp(term, "linux") ||
221 !strcmp(term, "cygwin");
224 return term_supports_color;
227 _START_GOOGLE_NAMESPACE_
236 static GLogColor SeverityToColor(LogSeverity severity) {
237 assert(severity >= 0 && severity < NUM_SEVERITIES);
238 GLogColor color = COLOR_DEFAULT;
241 color = COLOR_DEFAULT;
244 color = COLOR_YELLOW;
251 // should never get here.
259 // Returns the character attribute for the given color.
260 WORD GetColorAttribute(GLogColor color) {
262 case COLOR_RED: return FOREGROUND_RED;
263 case COLOR_GREEN: return FOREGROUND_GREEN;
264 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
271 // Returns the ANSI color code for the given color.
272 const char* GetAnsiColorCode(GLogColor color) {
274 case COLOR_RED: return "1";
275 case COLOR_GREEN: return "2";
276 case COLOR_YELLOW: return "3";
277 case COLOR_DEFAULT: return "";
279 return NULL; // stop warning about return type.
284 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
285 static int32 MaxLogSize() {
286 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
289 struct LogMessage::LogMessageData {
292 int preserved_errno_; // preserved errno
293 char* buf_; // buffer space for non FATAL messages
294 char* message_text_; // Complete message text (points to selected buffer)
295 LogStream* stream_alloc_;
297 char severity_; // What level is this LogMessage logged at?
298 int line_; // line number where logging call is.
299 void (LogMessage::*send_method_)(); // Call this in destructor to send
300 union { // At most one of these is used: union to keep the size low.
301 LogSink* sink_; // NULL or sink to send message to
302 std::vector<std::string>* outvec_; // NULL or vector to push message onto
303 std::string* message_; // NULL or string to write message into
305 time_t timestamp_; // Time of creation of LogMessage
306 struct ::tm tm_time_; // Time of creation of LogMessage
307 size_t num_prefix_chars_; // # of chars of prefix in this message
308 size_t num_chars_to_log_; // # of chars of msg to send to log
309 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
310 const char* basename_; // basename of file that called LOG
311 const char* fullname_; // fullname of file that called LOG
312 bool has_been_flushed_; // false => data has not been flushed
313 bool first_fatal_; // true => this was first fatal msg
318 LogMessageData(const LogMessageData&);
319 void operator=(const LogMessageData&);
322 // A mutex that allows only one thread to log at a time, to keep things from
323 // getting jumbled. Some other very uncommon logging operations (like
324 // changing the destination file for log messages of a given severity) also
325 // lock this mutex. Please be sure that anybody who might possibly need to
327 static Mutex log_mutex;
329 // Number of messages sent at each severity. Under log_mutex.
330 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
332 // Globally disable log writing (if disk is full)
333 static bool stop_writing = false;
335 const char*const LogSeverityNames[NUM_SEVERITIES] = {
336 "INFO", "WARNING", "ERROR", "FATAL"
339 // Has the user called SetExitOnDFatal(true)?
340 static bool exit_on_dfatal = true;
342 const char* GetLogSeverityName(LogSeverity severity) {
343 return LogSeverityNames[severity];
346 static bool SendEmailInternal(const char*dest, const char *subject,
347 const char*body, bool use_logging);
349 base::Logger::~Logger() {
354 // Encapsulates all file-system related state
355 class LogFileObject : public base::Logger {
357 LogFileObject(LogSeverity severity, const char* base_filename);
360 virtual void Write(bool force_flush, // Should we force a flush here?
361 time_t timestamp, // Timestamp for this entry
365 // Configuration options
366 void SetBasename(const char* basename);
367 void SetExtension(const char* ext);
368 void SetSymlinkBasename(const char* symlink_basename);
370 // Normal flushing routine
371 virtual void Flush();
373 // It is the actual file length for the system loggers,
374 // i.e., INFO, ERROR, etc.
375 virtual uint32 LogSize() {
380 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
381 // can avoid grabbing a lock. Usually Flush() calls it after
383 void FlushUnlocked();
386 static const uint32 kRolloverAttemptFrequency = 0x20;
389 bool base_filename_selected_;
390 string base_filename_;
391 string symlink_basename_;
392 string filename_extension_; // option users can specify (eg to add port#)
394 LogSeverity severity_;
395 uint32 bytes_since_flush_;
397 unsigned int rollover_attempt_;
398 int64 next_flush_time_; // cycle count at which to flush log
400 // Actually create a logfile using the value of base_filename_ and the
401 // supplied argument time_pid_string
402 // REQUIRES: lock_ is held
403 bool CreateLogfile(const string& time_pid_string);
408 class LogDestination {
410 friend class LogMessage;
411 friend void ReprintFatalMessage();
412 friend base::Logger* base::GetLogger(LogSeverity);
413 friend void base::SetLogger(LogSeverity, base::Logger*);
415 // These methods are just forwarded to by their global versions.
416 static void SetLogDestination(LogSeverity severity,
417 const char* base_filename);
418 static void SetLogSymlink(LogSeverity severity,
419 const char* symlink_basename);
420 static void AddLogSink(LogSink *destination);
421 static void RemoveLogSink(LogSink *destination);
422 static void SetLogFilenameExtension(const char* filename_extension);
423 static void SetStderrLogging(LogSeverity min_severity);
424 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
425 static void LogToStderr();
426 // Flush all log files that are at least at the given severity level
427 static void FlushLogFiles(int min_severity);
428 static void FlushLogFilesUnsafe(int min_severity);
430 // we set the maximum size of our packet to be 1400, the logic being
431 // to prevent fragmentation.
432 // Really this number is arbitrary.
433 static const int kNetworkBytes = 1400;
435 static const string& hostname();
436 static const bool& terminal_supports_color() {
437 return terminal_supports_color_;
440 static void DeleteLogDestinations();
443 LogDestination(LogSeverity severity, const char* base_filename);
444 ~LogDestination() { }
446 // Take a log message of a particular severity and log it to stderr
447 // iff it's of a high enough severity to deserve it.
448 static void MaybeLogToStderr(LogSeverity severity, const char* message,
451 // Take a log message of a particular severity and log it to email
452 // iff it's of a high enough severity to deserve it.
453 static void MaybeLogToEmail(LogSeverity severity, const char* message,
455 // Take a log message of a particular severity and log it to a file
456 // iff the base filename is not "" (which means "don't log to me")
457 static void MaybeLogToLogfile(LogSeverity severity,
459 const char* message, size_t len);
460 // Take a log message of a particular severity and log it to the file
461 // for that severity and also for all files with severity less than
463 static void LogToAllLogfiles(LogSeverity severity,
465 const char* message, size_t len);
467 // Send logging info to all registered sinks.
468 static void LogToSinks(LogSeverity severity,
469 const char *full_filename,
470 const char *base_filename,
472 const struct ::tm* tm_time,
476 // Wait for all registered sinks via WaitTillSent
477 // including the optional one in "data".
478 static void WaitForSinks(LogMessage::LogMessageData* data);
480 static LogDestination* log_destination(LogSeverity severity);
482 LogFileObject fileobject_;
483 base::Logger* logger_; // Either &fileobject_, or wrapper around it
485 static LogDestination* log_destinations_[NUM_SEVERITIES];
486 static LogSeverity email_logging_severity_;
487 static string addresses_;
488 static string hostname_;
489 static bool terminal_supports_color_;
491 // arbitrary global logging destinations.
492 static vector<LogSink*>* sinks_;
494 // Protects the vector sinks_,
495 // but not the LogSink objects its elements reference.
496 static Mutex sink_mutex_;
499 LogDestination(const LogDestination&);
500 LogDestination& operator=(const LogDestination&);
503 // Errors do not get logged to email by default.
504 LogSeverity LogDestination::email_logging_severity_ = 99999;
506 string LogDestination::addresses_;
507 string LogDestination::hostname_;
509 vector<LogSink*>* LogDestination::sinks_ = NULL;
510 Mutex LogDestination::sink_mutex_;
511 bool LogDestination::terminal_supports_color_ = TerminalSupportsColor();
514 const string& LogDestination::hostname() {
515 if (hostname_.empty()) {
516 GetHostName(&hostname_);
517 if (hostname_.empty()) {
518 hostname_ = "(unknown)";
524 LogDestination::LogDestination(LogSeverity severity,
525 const char* base_filename)
526 : fileobject_(severity, base_filename),
527 logger_(&fileobject_) {
530 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
531 // assume we have the log_mutex or we simply don't care
533 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
534 LogDestination* log = log_destination(i);
536 // Flush the base fileobject_ logger directly instead of going
537 // through any wrappers to reduce chance of deadlock.
538 log->fileobject_.FlushUnlocked();
543 inline void LogDestination::FlushLogFiles(int min_severity) {
544 // Prevent any subtle race conditions by wrapping a mutex lock around
546 MutexLock l(&log_mutex);
547 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
548 LogDestination* log = log_destination(i);
550 log->logger_->Flush();
555 inline void LogDestination::SetLogDestination(LogSeverity severity,
556 const char* base_filename) {
557 assert(severity >= 0 && severity < NUM_SEVERITIES);
558 // Prevent any subtle race conditions by wrapping a mutex lock around
560 MutexLock l(&log_mutex);
561 log_destination(severity)->fileobject_.SetBasename(base_filename);
564 inline void LogDestination::SetLogSymlink(LogSeverity severity,
565 const char* symlink_basename) {
566 CHECK_GE(severity, 0);
567 CHECK_LT(severity, NUM_SEVERITIES);
568 MutexLock l(&log_mutex);
569 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
572 inline void LogDestination::AddLogSink(LogSink *destination) {
573 // Prevent any subtle race conditions by wrapping a mutex lock around
575 MutexLock l(&sink_mutex_);
576 if (!sinks_) sinks_ = new vector<LogSink*>;
577 sinks_->push_back(destination);
580 inline void LogDestination::RemoveLogSink(LogSink *destination) {
581 // Prevent any subtle race conditions by wrapping a mutex lock around
583 MutexLock l(&sink_mutex_);
584 // This doesn't keep the sinks in order, but who cares?
586 for (int i = sinks_->size() - 1; i >= 0; i--) {
587 if ((*sinks_)[i] == destination) {
588 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
596 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
597 // Prevent any subtle race conditions by wrapping a mutex lock around
599 MutexLock l(&log_mutex);
600 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
601 log_destination(severity)->fileobject_.SetExtension(ext);
605 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
606 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
607 // Prevent any subtle race conditions by wrapping a mutex lock around
609 MutexLock l(&log_mutex);
610 FLAGS_stderrthreshold = min_severity;
613 inline void LogDestination::LogToStderr() {
614 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
615 // SetLogDestination already do the locking!
616 SetStderrLogging(0); // thus everything is "also" logged to stderr
617 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
618 SetLogDestination(i, ""); // "" turns off logging to a logfile
622 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
623 const char* addresses) {
624 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
625 // Prevent any subtle race conditions by wrapping a mutex lock around
627 MutexLock l(&log_mutex);
628 LogDestination::email_logging_severity_ = min_severity;
629 LogDestination::addresses_ = addresses;
632 static void ColoredWriteToStderr(const char* message, size_t len, GLogColor color) {
633 // Avoid using cerr from this module since we may get called during
634 // exit code, and cerr may be partially or fully destroyed by then.
635 if ( COLOR_DEFAULT == color ) {
636 fwrite(message, len, 1, stderr);
640 const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
642 // Gets the current text color.
643 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
644 GetConsoleScreenBufferInfo(stderr_handle, &buffer_info);
645 const WORD old_color_attrs = buffer_info.wAttributes;
647 // We need to flush the stream buffers into the console before each
648 // SetConsoleTextAttribute call lest it affect the text that is already
649 // printed but has not yet reached the console.
651 SetConsoleTextAttribute(stderr_handle,
652 GetColorAttribute(color) | FOREGROUND_INTENSITY);
653 fwrite(message, len, 1, stderr);
655 // Restores the text color.
656 SetConsoleTextAttribute(stderr_handle, old_color_attrs);
658 fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color));
659 fwrite(message, len, 1, stderr);
660 fprintf(stderr, "\033[m"); // Resets the terminal to default.
664 static void WriteToStderr(const char* message, size_t len) {
665 // Avoid using cerr from this module since we may get called during
666 // exit code, and cerr may be partially or fully destroyed by then.
667 fwrite(message, len, 1, stderr);
670 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
671 const char* message, size_t len) {
672 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
673 const GLogColor color =
674 (terminal_supports_color_ && FLAGS_colorstderr) ?
675 SeverityToColor(severity) : COLOR_DEFAULT;
676 ColoredWriteToStderr(message, len, color);
678 // On Windows, also output to the debugger
679 ::OutputDebugStringA(string(message,len).c_str());
685 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
686 const char* message, size_t len) {
687 if (severity >= email_logging_severity_ ||
688 severity >= FLAGS_logemaillevel) {
689 string to(FLAGS_alsologtoemail);
690 if (!addresses_.empty()) {
696 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
697 glog_internal_namespace_::ProgramInvocationShortName());
698 string body(hostname());
700 body.append(message, len);
702 // should NOT use SendEmail(). The caller of this function holds the
703 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
704 // acquire the log_mutex object. Use SendEmailInternal() and set
705 // use_logging to false.
706 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
711 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
715 const bool should_flush = severity > FLAGS_logbuflevel;
716 LogDestination* destination = log_destination(severity);
717 destination->logger_->Write(should_flush, timestamp, message, len);
720 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
725 if ( FLAGS_logtostderr ) { // global flag: never log to file
726 const GLogColor color =
727 (terminal_supports_color_ && FLAGS_colorstderr) ?
728 SeverityToColor(severity) : COLOR_DEFAULT;
729 ColoredWriteToStderr(message, len, color);
731 for (int i = severity; i >= 0; --i)
732 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
736 inline void LogDestination::LogToSinks(LogSeverity severity,
737 const char *full_filename,
738 const char *base_filename,
740 const struct ::tm* tm_time,
742 size_t message_len) {
743 ReaderMutexLock l(&sink_mutex_);
745 for (int i = sinks_->size() - 1; i >= 0; i--) {
746 (*sinks_)[i]->send(severity, full_filename, base_filename,
747 line, tm_time, message, message_len);
752 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
753 ReaderMutexLock l(&sink_mutex_);
755 for (int i = sinks_->size() - 1; i >= 0; i--) {
756 (*sinks_)[i]->WaitTillSent();
759 const bool send_to_sink =
760 (data->send_method_ == &LogMessage::SendToSink) ||
761 (data->send_method_ == &LogMessage::SendToSinkAndLog);
762 if (send_to_sink && data->sink_ != NULL) {
763 data->sink_->WaitTillSent();
767 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
769 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
770 assert(severity >=0 && severity < NUM_SEVERITIES);
771 if (!log_destinations_[severity]) {
772 log_destinations_[severity] = new LogDestination(severity, NULL);
774 return log_destinations_[severity];
777 void LogDestination::DeleteLogDestinations() {
778 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
779 delete log_destinations_[severity];
780 log_destinations_[severity] = NULL;
786 LogFileObject::LogFileObject(LogSeverity severity,
787 const char* base_filename)
788 : base_filename_selected_(base_filename != NULL),
789 base_filename_((base_filename != NULL) ? base_filename : ""),
790 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
791 filename_extension_(),
794 bytes_since_flush_(0),
796 rollover_attempt_(kRolloverAttemptFrequency-1),
797 next_flush_time_(0) {
798 assert(severity >= 0);
799 assert(severity < NUM_SEVERITIES);
802 LogFileObject::~LogFileObject() {
810 void LogFileObject::SetBasename(const char* basename) {
812 base_filename_selected_ = true;
813 if (base_filename_ != basename) {
814 // Get rid of old log file since we are changing names
818 rollover_attempt_ = kRolloverAttemptFrequency-1;
820 base_filename_ = basename;
824 void LogFileObject::SetExtension(const char* ext) {
826 if (filename_extension_ != ext) {
827 // Get rid of old log file since we are changing names
831 rollover_attempt_ = kRolloverAttemptFrequency-1;
833 filename_extension_ = ext;
837 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
839 symlink_basename_ = symlink_basename;
842 void LogFileObject::Flush() {
847 void LogFileObject::FlushUnlocked(){
850 bytes_since_flush_ = 0;
852 // Figure out when we are due for another flush.
853 const int64 next = (FLAGS_logbufsecs
854 * static_cast<int64>(1000000)); // in usec
855 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
858 bool LogFileObject::CreateLogfile(const string& time_pid_string) {
859 string string_filename = base_filename_+filename_extension_+
861 const char* filename = string_filename.c_str();
862 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
863 if (fd == -1) return false;
865 // Mark the file close-on-exec. We don't really care if this fails
866 fcntl(fd, F_SETFD, FD_CLOEXEC);
869 file_ = fdopen(fd, "a"); // Make a FILE*.
870 if (file_ == NULL) { // Man, we're screwed!
872 unlink(filename); // Erase the half-baked evidence: an unusable log file
876 // We try to create a symlink called <program_name>.<severity>,
877 // which is easier to use. (Every time we create a new logfile,
878 // we destroy the old symlink and create a new one, so it always
879 // points to the latest logfile.) If it fails, we're sad but it's
881 if (!symlink_basename_.empty()) {
882 // take directory from filename
883 const char* slash = strrchr(filename, PATH_SEPARATOR);
884 const string linkname =
885 symlink_basename_ + '.' + LogSeverityNames[severity_];
887 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
888 linkpath += linkname;
889 unlink(linkpath.c_str()); // delete old one if it exists
891 // We must have unistd.h.
893 // Make the symlink be relative (in the same dir) so that if the
894 // entire log directory gets relocated the link is still valid.
895 const char *linkdest = slash ? (slash + 1) : filename;
896 if (symlink(linkdest, linkpath.c_str()) != 0) {
897 // silently ignore failures
900 // Make an additional link to the log file in a place specified by
901 // FLAGS_log_link, if indicated
902 if (!FLAGS_log_link.empty()) {
903 linkpath = FLAGS_log_link + "/" + linkname;
904 unlink(linkpath.c_str()); // delete old one if it exists
905 if (symlink(filename, linkpath.c_str()) != 0) {
906 // silently ignore failures
912 return true; // Everything worked
915 void LogFileObject::Write(bool force_flush,
921 // We don't log if the base_name_ is "" (which means "don't write")
922 if (base_filename_selected_ && base_filename_.empty()) {
926 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
928 if (file_ != NULL) fclose(file_);
930 file_length_ = bytes_since_flush_ = 0;
931 rollover_attempt_ = kRolloverAttemptFrequency-1;
934 // If there's no destination file, make one before outputting
936 // Try to rollover the log file every 32 log messages. The only time
937 // this could matter would be when we have trouble creating the log
938 // file. If that happens, we'll lose lots of log messages, of course!
939 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
940 rollover_attempt_ = 0;
943 localtime_r(×tamp, &tm_time);
945 // The logfile's filename will have the date/time & pid in it
946 ostringstream time_pid_stream;
947 time_pid_stream.fill('0');
948 time_pid_stream << 1900+tm_time.tm_year
949 << setw(2) << 1+tm_time.tm_mon
950 << setw(2) << tm_time.tm_mday
952 << setw(2) << tm_time.tm_hour
953 << setw(2) << tm_time.tm_min
954 << setw(2) << tm_time.tm_sec
956 << GetMainThreadPid();
957 const string& time_pid_string = time_pid_stream.str();
959 if (base_filename_selected_) {
960 if (!CreateLogfile(time_pid_string)) {
961 perror("Could not create log file");
962 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
963 time_pid_string.c_str());
967 // If no base filename for logs of this severity has been set, use a
968 // default base filename of
969 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
970 // logfiles will have names like
971 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
972 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
973 // and 4354 is the pid of the logging process. The date & time reflect
974 // when the file was created for output.
976 // Where does the file get put? Successively try the directories
978 string stripped_filename(
979 glog_internal_namespace_::ProgramInvocationShortName());
981 GetHostName(&hostname);
983 string uidname = MyUserName();
984 // We should not call CHECK() here because this function can be
985 // called after holding on to log_mutex. We don't want to
986 // attempt to hold on to the same mutex, and get into a
987 // deadlock. Simply use a name like invalid-user.
988 if (uidname.empty()) uidname = "invalid-user";
990 stripped_filename = stripped_filename+'.'+hostname+'.'
992 +LogSeverityNames[severity_]+'.';
993 // We're going to (potentially) try to put logs in several different dirs
994 const vector<string> & log_dirs = GetLoggingDirectories();
996 // Go through the list of dirs, and try to create the log file in each
997 // until we succeed or run out of options
998 bool success = false;
999 for (vector<string>::const_iterator dir = log_dirs.begin();
1000 dir != log_dirs.end();
1002 base_filename_ = *dir + "/" + stripped_filename;
1003 if ( CreateLogfile(time_pid_string) ) {
1008 // If we never succeeded, we have to give up
1009 if ( success == false ) {
1010 perror("Could not create logging file");
1011 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
1012 time_pid_string.c_str());
1017 // Write a header message into the log file
1018 ostringstream file_header_stream;
1019 file_header_stream.fill('0');
1020 file_header_stream << "Log file created at: "
1021 << 1900+tm_time.tm_year << '/'
1022 << setw(2) << 1+tm_time.tm_mon << '/'
1023 << setw(2) << tm_time.tm_mday
1025 << setw(2) << tm_time.tm_hour << ':'
1026 << setw(2) << tm_time.tm_min << ':'
1027 << setw(2) << tm_time.tm_sec << '\n'
1028 << "Running on machine: "
1029 << LogDestination::hostname() << '\n'
1030 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
1031 << "threadid file:line] msg" << '\n';
1032 const string& file_header_string = file_header_stream.str();
1034 const int header_len = file_header_string.size();
1035 fwrite(file_header_string.data(), 1, header_len, file_);
1036 file_length_ += header_len;
1037 bytes_since_flush_ += header_len;
1040 // Write to LOG file
1041 if ( !stop_writing ) {
1042 // fwrite() doesn't return an error when the disk is full, for
1043 // messages that are less than 4096 bytes. When the disk is full,
1044 // it returns the message length for messages that are less than
1045 // 4096 bytes. fwrite() returns 4096 for message lengths that are
1046 // greater than 4096, thereby indicating an error.
1048 fwrite(message, 1, message_len, file_);
1049 if ( FLAGS_stop_logging_if_full_disk &&
1050 errno == ENOSPC ) { // disk full, stop writing to disk
1051 stop_writing = true; // until the disk is
1054 file_length_ += message_len;
1055 bytes_since_flush_ += message_len;
1058 if ( CycleClock_Now() >= next_flush_time_ )
1059 stop_writing = false; // check to see if disk has free space.
1060 return; // no need to flush
1063 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
1064 // or every "FLAGS_logbufsecs" seconds.
1066 (bytes_since_flush_ >= 1000000) ||
1067 (CycleClock_Now() >= next_flush_time_) ) {
1070 if (FLAGS_drop_log_memory) {
1071 if (file_length_ >= logging::kPageSize) {
1072 // don't evict the most recent page
1073 uint32 len = file_length_ & ~(logging::kPageSize - 1);
1074 posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
1083 // An arbitrary limit on the length of a single log message. This
1084 // is so that streaming can be done more efficiently.
1085 const size_t LogMessage::kMaxLogMessageLen = 30000;
1087 // Static log data space to avoid alloc failures in a LOG(FATAL)
1089 // Since multiple threads may call LOG(FATAL), and we want to preserve
1090 // the data from the first call, we allocate two sets of space. One
1091 // for exclusive use by the first thread, and one for shared use by
1092 // all other threads.
1093 static Mutex fatal_msg_lock;
1094 static CrashReason crash_reason;
1095 static bool fatal_msg_exclusive = true;
1096 static char fatal_msg_buf_exclusive[LogMessage::kMaxLogMessageLen+1];
1097 static char fatal_msg_buf_shared[LogMessage::kMaxLogMessageLen+1];
1098 static LogMessage::LogStream fatal_msg_stream_exclusive(
1099 fatal_msg_buf_exclusive, LogMessage::kMaxLogMessageLen, 0);
1100 static LogMessage::LogStream fatal_msg_stream_shared(
1101 fatal_msg_buf_shared, LogMessage::kMaxLogMessageLen, 0);
1102 static LogMessage::LogMessageData fatal_msg_data_exclusive;
1103 static LogMessage::LogMessageData fatal_msg_data_shared;
1105 LogMessage::LogMessageData::~LogMessageData() {
1107 delete stream_alloc_;
1110 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1111 int ctr, void (LogMessage::*send_method)())
1112 : allocated_(NULL) {
1113 Init(file, line, severity, send_method);
1114 data_->stream_->set_ctr(ctr);
1117 LogMessage::LogMessage(const char* file, int line,
1118 const CheckOpString& result)
1119 : allocated_(NULL) {
1120 Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
1121 stream() << "Check failed: " << (*result.str_) << " ";
1124 LogMessage::LogMessage(const char* file, int line)
1125 : allocated_(NULL) {
1126 Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
1129 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
1130 : allocated_(NULL) {
1131 Init(file, line, severity, &LogMessage::SendToLog);
1134 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1135 LogSink* sink, bool also_send_to_log)
1136 : allocated_(NULL) {
1137 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
1138 &LogMessage::SendToSink);
1139 data_->sink_ = sink; // override Init()'s setting to NULL
1142 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1143 vector<string> *outvec)
1144 : allocated_(NULL) {
1145 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
1146 data_->outvec_ = outvec; // override Init()'s setting to NULL
1149 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1151 : allocated_(NULL) {
1152 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
1153 data_->message_ = message; // override Init()'s setting to NULL
1156 void LogMessage::Init(const char* file,
1158 LogSeverity severity,
1159 void (LogMessage::*send_method)()) {
1161 if (severity != GLOG_FATAL || !exit_on_dfatal) {
1162 allocated_ = new LogMessageData();
1164 data_->buf_ = new char[kMaxLogMessageLen+1];
1165 data_->message_text_ = data_->buf_;
1166 data_->stream_alloc_ =
1167 new LogStream(data_->message_text_, kMaxLogMessageLen, 0);
1168 data_->stream_ = data_->stream_alloc_;
1169 data_->first_fatal_ = false;
1171 MutexLock l(&fatal_msg_lock);
1172 if (fatal_msg_exclusive) {
1173 fatal_msg_exclusive = false;
1174 data_ = &fatal_msg_data_exclusive;
1175 data_->message_text_ = fatal_msg_buf_exclusive;
1176 data_->stream_ = &fatal_msg_stream_exclusive;
1177 data_->first_fatal_ = true;
1179 data_ = &fatal_msg_data_shared;
1180 data_->message_text_ = fatal_msg_buf_shared;
1181 data_->stream_ = &fatal_msg_stream_shared;
1182 data_->first_fatal_ = false;
1184 data_->stream_alloc_ = NULL;
1188 data_->preserved_errno_ = errno;
1189 data_->severity_ = severity;
1190 data_->line_ = line;
1191 data_->send_method_ = send_method;
1192 data_->sink_ = NULL;
1193 data_->outvec_ = NULL;
1194 WallTime now = WallTime_Now();
1195 data_->timestamp_ = static_cast<time_t>(now);
1196 localtime_r(&data_->timestamp_, &data_->tm_time_);
1197 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1198 RawLog__SetLastTime(data_->tm_time_, usecs);
1200 data_->num_chars_to_log_ = 0;
1201 data_->num_chars_to_syslog_ = 0;
1202 data_->basename_ = const_basename(file);
1203 data_->fullname_ = file;
1204 data_->has_been_flushed_ = false;
1206 // If specified, prepend a prefix to each line. For example:
1207 // I1018 160715 f5d4fbb0 logging.cc:1153]
1208 // (log level, GMT month, date, time, thread_id, file basename, line)
1209 // We exclude the thread_id for the default thread.
1210 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1211 stream() << LogSeverityNames[severity][0]
1212 << setw(2) << 1+data_->tm_time_.tm_mon
1213 << setw(2) << data_->tm_time_.tm_mday
1215 << setw(2) << data_->tm_time_.tm_hour << ':'
1216 << setw(2) << data_->tm_time_.tm_min << ':'
1217 << setw(2) << data_->tm_time_.tm_sec << "."
1220 << setfill(' ') << setw(5)
1221 << static_cast<unsigned int>(GetTID()) << setfill('0')
1223 << data_->basename_ << ':' << data_->line_ << "] ";
1225 data_->num_prefix_chars_ = data_->stream_->pcount();
1227 if (!FLAGS_log_backtrace_at.empty()) {
1229 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1230 #ifdef HAVE_STACKTRACE
1231 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1233 DumpStackTraceToString(&stacktrace);
1234 stream() << " (stacktrace:\n" << stacktrace << ") ";
1240 LogMessage::~LogMessage() {
1245 int LogMessage::preserved_errno() const {
1246 return data_->preserved_errno_;
1249 ostream& LogMessage::stream() {
1250 return *(data_->stream_);
1253 // Flush buffered message, called by the destructor, or any other function
1254 // that needs to synchronize the log.
1255 void LogMessage::Flush() {
1256 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1259 data_->num_chars_to_log_ = data_->stream_->pcount();
1260 data_->num_chars_to_syslog_ =
1261 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1263 // Do we need to add a \n to the end of this message?
1264 bool append_newline =
1265 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1266 char original_final_char = '\0';
1268 // If we do need to add a \n, we'll do it by violating the memory of the
1269 // ostrstream buffer. This is quick, and we'll make sure to undo our
1270 // modification before anything else is done with the ostrstream. It
1271 // would be preferable not to do things this way, but it seems to be
1272 // the best way to deal with this.
1273 if (append_newline) {
1274 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1275 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1278 // Prevent any subtle race conditions by wrapping a mutex lock around
1279 // the actual logging action per se.
1281 MutexLock l(&log_mutex);
1282 (this->*(data_->send_method_))();
1283 ++num_messages_[static_cast<int>(data_->severity_)];
1285 LogDestination::WaitForSinks(data_);
1287 if (append_newline) {
1288 // Fix the ostrstream back how it was before we screwed with it.
1289 // It's 99.44% certain that we don't need to worry about doing this.
1290 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1293 // If errno was already set before we enter the logging call, we'll
1294 // set it back to that value when we return from the logging call.
1295 // It happens often that we log an error message after a syscall
1296 // failure, which can potentially set the errno to some other
1297 // values. We would like to preserve the original errno.
1298 if (data_->preserved_errno_ != 0) {
1299 errno = data_->preserved_errno_;
1302 // Note that this message is now safely logged. If we're asked to flush
1303 // again, as a result of destruction, say, we'll do nothing on future calls.
1304 data_->has_been_flushed_ = true;
1307 // Copy of first FATAL log message so that we can print it out again
1308 // after all the stack traces. To preserve legacy behavior, we don't
1309 // use fatal_msg_buf_exclusive.
1310 static time_t fatal_time;
1311 static char fatal_message[256];
1313 void ReprintFatalMessage() {
1314 if (fatal_message[0]) {
1315 const int n = strlen(fatal_message);
1316 if (!FLAGS_logtostderr) {
1317 // Also write to stderr (don't color to avoid terminal checks)
1318 WriteToStderr(fatal_message, n);
1320 LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1324 // L >= log_mutex (callers must hold the log_mutex).
1325 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1326 static bool already_warned_before_initgoogle = false;
1328 log_mutex.AssertHeld();
1330 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1331 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1333 // Messages of a given severity get logged to lower severity logs, too
1335 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1336 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1337 "written to STDERR\n";
1338 WriteToStderr(w, strlen(w));
1339 already_warned_before_initgoogle = true;
1342 // global flag: never log to file if set. Also -- don't log to a
1343 // file if we haven't parsed the command line flags to get the
1345 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1346 const GLogColor color =
1347 (LogDestination::terminal_supports_color() && FLAGS_colorstderr) ?
1348 SeverityToColor(data_->severity_) : COLOR_DEFAULT;
1349 ColoredWriteToStderr(data_->message_text_, data_->num_chars_to_log_, color);
1351 // this could be protected by a flag if necessary.
1352 LogDestination::LogToSinks(data_->severity_,
1353 data_->fullname_, data_->basename_,
1354 data_->line_, &data_->tm_time_,
1355 data_->message_text_ + data_->num_prefix_chars_,
1356 (data_->num_chars_to_log_ -
1357 data_->num_prefix_chars_ - 1));
1360 // log this message to all log files of severity <= severity_
1361 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1362 data_->message_text_,
1363 data_->num_chars_to_log_);
1365 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1366 data_->num_chars_to_log_);
1367 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1368 data_->num_chars_to_log_);
1369 LogDestination::LogToSinks(data_->severity_,
1370 data_->fullname_, data_->basename_,
1371 data_->line_, &data_->tm_time_,
1372 data_->message_text_ + data_->num_prefix_chars_,
1373 (data_->num_chars_to_log_
1374 - data_->num_prefix_chars_ - 1));
1375 // NOTE: -1 removes trailing \n
1378 // If we log a FATAL message, flush all the log destinations, then toss
1379 // a signal for others to catch. We leave the logs in a state that
1380 // someone else can use them (as long as they flush afterwards)
1381 if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1382 if (data_->first_fatal_) {
1383 // Store crash information so that it is accessible from within signal
1384 // handlers that may be invoked later.
1385 RecordCrashReason(&crash_reason);
1386 SetCrashReason(&crash_reason);
1388 // Store shortened fatal message for other logs and GWQ status
1389 const int copy = min<int>(data_->num_chars_to_log_,
1390 sizeof(fatal_message)-1);
1391 memcpy(fatal_message, data_->message_text_, copy);
1392 fatal_message[copy] = '\0';
1393 fatal_time = data_->timestamp_;
1396 if (!FLAGS_logtostderr) {
1397 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1398 if ( LogDestination::log_destinations_[i] )
1399 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1403 // release the lock that our caller (directly or indirectly)
1404 // LogMessage::~LogMessage() grabbed so that signal handlers
1405 // can use the logging facility. Alternately, we could add
1406 // an entire unsafe logging interface to bypass locking
1407 // for signal handlers but this seems simpler.
1409 LogDestination::WaitForSinks(data_);
1411 const char* message = "*** Check failure stack trace: ***\n";
1412 if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1419 void LogMessage::RecordCrashReason(
1420 glog_internal_namespace_::CrashReason* reason) {
1421 reason->filename = fatal_msg_data_exclusive.fullname_;
1422 reason->line_number = fatal_msg_data_exclusive.line_;
1423 reason->message = fatal_msg_buf_exclusive +
1424 fatal_msg_data_exclusive.num_prefix_chars_;
1425 #ifdef HAVE_STACKTRACE
1426 // Retrieve the stack trace, omitting the logging frames that got us here.
1427 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1433 #ifdef HAVE___ATTRIBUTE__
1434 # define ATTRIBUTE_NORETURN __attribute__((noreturn))
1436 # define ATTRIBUTE_NORETURN
1439 static void logging_fail() ATTRIBUTE_NORETURN;
1441 static void logging_fail() {
1442 #if defined(_DEBUG) && defined(_MSC_VER)
1443 // When debugging on windows, avoid the obnoxious dialog and make
1444 // it possible to continue past a LOG(FATAL) in the debugger
1451 typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN;
1453 GOOGLE_GLOG_DLL_DECL
1454 logging_fail_func_t g_logging_fail_func = &logging_fail;
1456 void InstallFailureFunction(void (*fail_func)()) {
1457 g_logging_fail_func = (logging_fail_func_t)fail_func;
1460 void LogMessage::Fail() {
1461 g_logging_fail_func();
1464 // L >= log_mutex (callers must hold the log_mutex).
1465 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1466 if (data_->sink_ != NULL) {
1467 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1468 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1469 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1470 data_->line_, &data_->tm_time_,
1471 data_->message_text_ + data_->num_prefix_chars_,
1472 (data_->num_chars_to_log_ -
1473 data_->num_prefix_chars_ - 1));
1477 // L >= log_mutex (callers must hold the log_mutex).
1478 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1483 // L >= log_mutex (callers must hold the log_mutex).
1484 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1485 if (data_->outvec_ != NULL) {
1486 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1487 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1488 // Omit prefix of message and trailing newline when recording in outvec_.
1489 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1490 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1491 data_->outvec_->push_back(string(start, len));
1497 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1498 if (data_->message_ != NULL) {
1499 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1500 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1501 // Omit prefix of message and trailing newline when writing to message_.
1502 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1503 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1504 data_->message_->assign(start, len);
1509 // L >= log_mutex (callers must hold the log_mutex).
1510 void LogMessage::SendToSyslogAndLog() {
1511 #ifdef HAVE_SYSLOG_H
1512 // Before any calls to syslog(), make a single call to openlog()
1513 static bool openlog_already_called = false;
1514 if (!openlog_already_called) {
1515 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1516 LOG_CONS | LOG_NDELAY | LOG_PID,
1518 openlog_already_called = true;
1521 // This array maps Google severity levels to syslog levels
1522 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1523 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1524 int(data_->num_chars_to_syslog_),
1525 data_->message_text_ + data_->num_prefix_chars_);
1528 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1532 base::Logger* base::GetLogger(LogSeverity severity) {
1533 MutexLock l(&log_mutex);
1534 return LogDestination::log_destination(severity)->logger_;
1537 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1538 MutexLock l(&log_mutex);
1539 LogDestination::log_destination(severity)->logger_ = logger;
1542 // L < log_mutex. Acquires and releases mutex_.
1543 int64 LogMessage::num_messages(int severity) {
1544 MutexLock l(&log_mutex);
1545 return num_messages_[severity];
1548 // Output the COUNTER value. This is only valid if ostream is a
1550 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1552 LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
1554 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1556 CHECK(log && log == log->self())
1557 << "You must not use COUNTER with non-glog ostream";
1562 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1563 LogSeverity severity, int ctr,
1564 void (LogMessage::*send_method)())
1565 : LogMessage(file, line, severity, ctr, send_method) {
1568 ErrnoLogMessage::~ErrnoLogMessage() {
1569 // Don't access errno directly because it may have been altered
1570 // while streaming the message.
1572 posix_strerror_r(preserved_errno(), buf, sizeof(buf));
1573 stream() << ": " << buf << " [" << preserved_errno() << "]";
1576 void FlushLogFiles(LogSeverity min_severity) {
1577 LogDestination::FlushLogFiles(min_severity);
1580 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1581 LogDestination::FlushLogFilesUnsafe(min_severity);
1584 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1585 LogDestination::SetLogDestination(severity, base_filename);
1588 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1589 LogDestination::SetLogSymlink(severity, symlink_basename);
1592 LogSink::~LogSink() {
1595 void LogSink::WaitTillSent() {
1599 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1600 const struct ::tm* tm_time,
1601 const char* message, size_t message_len) {
1602 ostringstream stream(string(message, message_len));
1605 // FIXME(jrvb): Updating this to use the correct value for usecs
1606 // requires changing the signature for both this method and
1607 // LogSink::send(). This change needs to be done in a separate CL
1608 // so subclasses of LogSink can be updated at the same time.
1611 stream << LogSeverityNames[severity][0]
1612 << setw(2) << 1+tm_time->tm_mon
1613 << setw(2) << tm_time->tm_mday
1615 << setw(2) << tm_time->tm_hour << ':'
1616 << setw(2) << tm_time->tm_min << ':'
1617 << setw(2) << tm_time->tm_sec << '.'
1620 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1622 << file << ':' << line << "] ";
1624 stream << string(message, message_len);
1625 return stream.str();
1628 void AddLogSink(LogSink *destination) {
1629 LogDestination::AddLogSink(destination);
1632 void RemoveLogSink(LogSink *destination) {
1633 LogDestination::RemoveLogSink(destination);
1636 void SetLogFilenameExtension(const char* ext) {
1637 LogDestination::SetLogFilenameExtension(ext);
1640 void SetStderrLogging(LogSeverity min_severity) {
1641 LogDestination::SetStderrLogging(min_severity);
1644 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1645 LogDestination::SetEmailLogging(min_severity, addresses);
1648 void LogToStderr() {
1649 LogDestination::LogToStderr();
1653 namespace internal {
1655 bool GetExitOnDFatal() {
1656 MutexLock l(&log_mutex);
1657 return exit_on_dfatal;
1660 // Determines whether we exit the program for a LOG(DFATAL) message in
1661 // debug mode. It does this by skipping the call to Fail/FailQuietly.
1662 // This is intended for testing only.
1664 // This can have some effects on LOG(FATAL) as well. Failure messages
1665 // are always allocated (rather than sharing a buffer), the crash
1666 // reason is not recorded, the "gwq" status message is not updated,
1667 // and the stack trace is not recorded. The LOG(FATAL) *will* still
1668 // exit the program. Since this function is used only in testing,
1669 // these differences are acceptable.
1670 void SetExitOnDFatal(bool value) {
1671 MutexLock l(&log_mutex);
1672 exit_on_dfatal = value;
1675 } // namespace internal
1678 // use_logging controls whether the logging functions LOG/VLOG are used
1679 // to log errors. It should be set to false when the caller holds the
1681 static bool SendEmailInternal(const char*dest, const char *subject,
1682 const char*body, bool use_logging) {
1683 if (dest && *dest) {
1684 if ( use_logging ) {
1685 VLOG(1) << "Trying to send TITLE:" << subject
1686 << " BODY:" << body << " to " << dest;
1688 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1689 subject, body, dest);
1693 FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1694 FILE* pipe = popen(cmd.c_str(), "w");
1696 // Add the body if we have one
1698 fwrite(body, sizeof(char), strlen(body), pipe);
1699 bool ok = pclose(pipe) != -1;
1701 if ( use_logging ) {
1703 posix_strerror_r(errno, buf, sizeof(buf));
1704 LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf;
1707 posix_strerror_r(errno, buf, sizeof(buf));
1708 fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf);
1713 if ( use_logging ) {
1714 LOG(ERROR) << "Unable to send mail to " << dest;
1716 fprintf(stderr, "Unable to send mail to %s\n", dest);
1723 bool SendEmail(const char*dest, const char *subject, const char*body){
1724 return SendEmailInternal(dest, subject, body, true);
1727 static void GetTempDirectories(vector<string>* list) {
1730 // On windows we'll try to find a directory in this order:
1731 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1734 // C:/WINDOWS/ or C:/WINNT/
1737 if (GetTempPathA(MAX_PATH, tmp))
1738 list->push_back(tmp);
1739 list->push_back("C:\\tmp\\");
1740 list->push_back("C:\\temp\\");
1742 // Directories, in order of preference. If we find a dir that
1743 // exists, we stop adding other less-preferred dirs
1744 const char * candidates[] = {
1745 // Non-null only during unittest/regtest
1746 getenv("TEST_TMPDIR"),
1748 // Explicitly-supplied temp dirs
1749 getenv("TMPDIR"), getenv("TMP"),
1751 // If all else fails
1755 for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
1756 const char *d = candidates[i];
1757 if (!d) continue; // Empty env var
1759 // Make sure we don't surprise anyone who's expecting a '/'
1761 if (dstr[dstr.size() - 1] != '/') {
1764 list->push_back(dstr);
1766 struct stat statbuf;
1767 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1768 // We found a dir that exists - we're done.
1776 static vector<string>* logging_directories_list;
1778 const vector<string>& GetLoggingDirectories() {
1779 // Not strictly thread-safe but we're called early in InitGoogle().
1780 if (logging_directories_list == NULL) {
1781 logging_directories_list = new vector<string>;
1783 if ( !FLAGS_log_dir.empty() ) {
1784 // A dir was specified, we should use it
1785 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1787 GetTempDirectories(logging_directories_list);
1790 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1791 logging_directories_list->push_back(tmp);
1792 logging_directories_list->push_back(".\\");
1794 logging_directories_list->push_back("./");
1798 return *logging_directories_list;
1801 void TestOnly_ClearLoggingDirectoriesList() {
1802 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1803 "called from test code.\n");
1804 delete logging_directories_list;
1805 logging_directories_list = NULL;
1808 void GetExistingTempDirectories(vector<string>* list) {
1809 GetTempDirectories(list);
1810 vector<string>::iterator i_dir = list->begin();
1811 while( i_dir != list->end() ) {
1812 // zero arg to access means test for existence; no constant
1813 // defined on windows
1814 if ( access(i_dir->c_str(), 0) ) {
1815 i_dir = list->erase(i_dir);
1822 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1823 #ifdef HAVE_UNISTD_H
1824 struct stat statbuf;
1825 const int kCopyBlockSize = 8 << 10;
1826 char copybuf[kCopyBlockSize];
1827 int64 read_offset, write_offset;
1828 // Don't follow symlinks unless they're our own fd symlinks in /proc
1830 const char *procfd_prefix = "/proc/self/fd/";
1831 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1833 int fd = open(path, flags);
1835 if (errno == EFBIG) {
1836 // The log file in question has got too big for us to open. The
1837 // real fix for this would be to compile logging.cc (or probably
1838 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1840 // Instead just truncate the file to something we can manage
1841 if (truncate(path, 0) == -1) {
1842 PLOG(ERROR) << "Unable to truncate " << path;
1844 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1847 PLOG(ERROR) << "Unable to open " << path;
1852 if (fstat(fd, &statbuf) == -1) {
1853 PLOG(ERROR) << "Unable to fstat()";
1857 // See if the path refers to a regular file bigger than the
1859 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1860 if (statbuf.st_size <= limit) goto out_close_fd;
1861 if (statbuf.st_size <= keep) goto out_close_fd;
1863 // This log file is too large - we need to truncate it
1864 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1866 // Copy the last "keep" bytes of the file to the beginning of the file
1867 read_offset = statbuf.st_size - keep;
1869 int bytesin, bytesout;
1870 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1871 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1872 if (bytesout == -1) {
1873 PLOG(ERROR) << "Unable to write to " << path;
1875 } else if (bytesout != bytesin) {
1876 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1878 read_offset += bytesin;
1879 write_offset += bytesout;
1881 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1883 // Truncate the remainder of the file. If someone else writes to the
1884 // end of the file after our last read() above, we lose their latest
1885 // data. Too bad ...
1886 if (ftruncate(fd, write_offset) == -1) {
1887 PLOG(ERROR) << "Unable to truncate " << path;
1893 LOG(ERROR) << "No log truncation support.";
1897 void TruncateStdoutStderr() {
1898 #ifdef HAVE_UNISTD_H
1899 int64 limit = MaxLogSize() << 20;
1900 int64 keep = 1 << 20;
1901 TruncateLogFile("/proc/self/fd/1", limit, keep);
1902 TruncateLogFile("/proc/self/fd/2", limit, keep);
1904 LOG(ERROR) << "No log truncation support.";
1909 // Helper functions for string comparisons.
1910 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1911 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1912 const char* names) { \
1913 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1914 if (equal == expected) return NULL; \
1919 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1920 return new string(ss.str()); \
1923 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1924 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1925 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1926 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1927 #undef DEFINE_CHECK_STROP_IMPL
1929 int posix_strerror_r(int err, char *buf, size_t len) {
1930 // Sanity check input parameters
1931 if (buf == NULL || len <= 0) {
1936 // Reset buf and errno, and try calling whatever version of strerror_r()
1937 // is implemented by glibc
1939 int old_errno = errno;
1941 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1943 // Both versions set errno on failure
1945 // Should already be there, but better safe than sorry
1951 // POSIX is vague about whether the string will be terminated, although
1952 // is indirectly implies that typically ERANGE will be returned, instead
1953 // of truncating the string. This is different from the GNU implementation.
1954 // We play it safe by always terminating the string explicitly.
1955 buf[len-1] = '\000';
1957 // If the function succeeded, we can use its exit code to determine the
1958 // semantics implemented by glibc
1962 // GNU semantics detected
1967 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
1968 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
1969 // This means an error on MacOSX or FreeBSD.
1973 strncat(buf, rc, len-1);
1979 LogMessageFatal::LogMessageFatal(const char* file, int line) :
1980 LogMessage(file, line, GLOG_FATAL) {}
1982 LogMessageFatal::LogMessageFatal(const char* file, int line,
1983 const CheckOpString& result) :
1984 LogMessage(file, line, result) {}
1986 LogMessageFatal::~LogMessageFatal() {
1993 CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
1994 : stream_(new ostringstream) {
1995 *stream_ << exprtext << " (";
1998 CheckOpMessageBuilder::~CheckOpMessageBuilder() {
2002 ostream* CheckOpMessageBuilder::ForVar2() {
2003 *stream_ << " vs. ";
2007 string* CheckOpMessageBuilder::NewString() {
2009 return new string(stream_->str());
2015 void MakeCheckOpValueString(std::ostream* os, const char& v) {
2016 if (v >= 32 && v <= 126) {
2017 (*os) << "'" << v << "'";
2019 (*os) << "char value " << (short)v;
2024 void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
2025 if (v >= 32 && v <= 126) {
2026 (*os) << "'" << v << "'";
2028 (*os) << "signed char value " << (short)v;
2033 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
2034 if (v >= 32 && v <= 126) {
2035 (*os) << "'" << v << "'";
2037 (*os) << "unsigned char value " << (unsigned short)v;
2041 void InitGoogleLogging(const char* argv0) {
2042 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
2045 void ShutdownGoogleLogging() {
2046 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
2047 LogDestination::DeleteLogDestinations();
2048 delete logging_directories_list;
2049 logging_directories_list = NULL;
2052 _END_GOOGLE_NAMESPACE_