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;
92 #define fdopen _fdopen
95 // There is no thread annotation support.
96 #define EXCLUSIVE_LOCKS_REQUIRED(mu)
98 static bool BoolFromEnv(const char *varname, bool defval) {
99 const char* const valstr = getenv(varname);
103 return memchr("tTyY1\0", valstr[0], 6) != NULL;
106 GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
107 "log messages go to stderr instead of logfiles");
108 GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
109 "log messages go to stderr in addition to logfiles");
110 GLOG_DEFINE_bool(colorlogtostderr, false,
111 "color messages logged to stderr (if supported by terminal)");
113 GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
114 "Logs can grow very quickly and they are rarely read before they "
115 "need to be evicted from memory. Instead, drop them from memory "
116 "as soon as they are flushed to disk.");
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_int32(logfile_mode, 0664, "Log file mode/permissions.");
165 GLOG_DEFINE_string(log_dir, DefaultLogDir(),
166 "If specified, logfiles are written into this directory instead "
167 "of the default logging directory.");
168 GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
169 "files in this directory");
171 GLOG_DEFINE_int32(max_log_size, 1800,
172 "approx. maximum log file size (in MB). A value of 0 will "
173 "be silently overridden to 1.");
175 GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
176 "Stop attempting to log to disk if the disk is full.");
178 GLOG_DEFINE_string(log_backtrace_at, "",
179 "Emit a backtrace when logging at file:linenum.");
181 // TODO(hamaji): consider windows
182 #define PATH_SEPARATOR '/'
185 #if defined(OS_WINDOWS)
187 #define ssize_t SSIZE_T
189 static ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
190 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
191 if (orig_offset == (off_t)-1)
193 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
195 ssize_t len = read(fd, buf, count);
198 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
202 #endif // !HAVE_PREAD
205 static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) {
206 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
207 if (orig_offset == (off_t)-1)
209 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
211 ssize_t len = write(fd, buf, count);
214 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
218 #endif // !HAVE_PWRITE
220 static void GetHostName(string* hostname) {
221 #if defined(HAVE_SYS_UTSNAME_H)
223 if (0 != uname(&buf)) {
224 // ensure null termination on failure
225 *buf.nodename = '\0';
227 *hostname = buf.nodename;
228 #elif defined(OS_WINDOWS)
229 char buf[MAX_COMPUTERNAME_LENGTH + 1];
230 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
231 if (GetComputerNameA(buf, &len)) {
237 # warning There is no way to retrieve the host name.
238 *hostname = "(unknown)";
242 // Returns true iff terminal supports using colors in output.
243 static bool TerminalSupportsColor() {
244 bool term_supports_color = false;
246 // on Windows TERM variable is usually not set, but the console does
248 term_supports_color = true;
250 // On non-Windows platforms, we rely on the TERM variable.
251 const char* const term = getenv("TERM");
252 if (term != NULL && term[0] != '\0') {
253 term_supports_color =
254 !strcmp(term, "xterm") ||
255 !strcmp(term, "xterm-color") ||
256 !strcmp(term, "xterm-256color") ||
257 !strcmp(term, "screen-256color") ||
258 !strcmp(term, "screen") ||
259 !strcmp(term, "linux") ||
260 !strcmp(term, "cygwin");
263 return term_supports_color;
266 _START_GOOGLE_NAMESPACE_
275 static GLogColor SeverityToColor(LogSeverity severity) {
276 assert(severity >= 0 && severity < NUM_SEVERITIES);
277 GLogColor color = COLOR_DEFAULT;
280 color = COLOR_DEFAULT;
283 color = COLOR_YELLOW;
290 // should never get here.
298 // Returns the character attribute for the given color.
299 WORD GetColorAttribute(GLogColor color) {
301 case COLOR_RED: return FOREGROUND_RED;
302 case COLOR_GREEN: return FOREGROUND_GREEN;
303 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
310 // Returns the ANSI color code for the given color.
311 const char* GetAnsiColorCode(GLogColor color) {
313 case COLOR_RED: return "1";
314 case COLOR_GREEN: return "2";
315 case COLOR_YELLOW: return "3";
316 case COLOR_DEFAULT: return "";
318 return NULL; // stop warning about return type.
323 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
324 static int32 MaxLogSize() {
325 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
328 // An arbitrary limit on the length of a single log message. This
329 // is so that streaming can be done more efficiently.
330 const size_t LogMessage::kMaxLogMessageLen = 30000;
332 struct LogMessage::LogMessageData {
335 int preserved_errno_; // preserved errno
336 // Buffer space; contains complete message text.
337 char message_text_[LogMessage::kMaxLogMessageLen+1];
339 char severity_; // What level is this LogMessage logged at?
340 int line_; // line number where logging call is.
341 void (LogMessage::*send_method_)(); // Call this in destructor to send
342 union { // At most one of these is used: union to keep the size low.
343 LogSink* sink_; // NULL or sink to send message to
344 std::vector<std::string>* outvec_; // NULL or vector to push message onto
345 std::string* message_; // NULL or string to write message into
347 time_t timestamp_; // Time of creation of LogMessage
348 struct ::tm tm_time_; // Time of creation of LogMessage
349 size_t num_prefix_chars_; // # of chars of prefix in this message
350 size_t num_chars_to_log_; // # of chars of msg to send to log
351 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
352 const char* basename_; // basename of file that called LOG
353 const char* fullname_; // fullname of file that called LOG
354 bool has_been_flushed_; // false => data has not been flushed
355 bool first_fatal_; // true => this was first fatal msg
358 LogMessageData(const LogMessageData&);
359 void operator=(const LogMessageData&);
362 // A mutex that allows only one thread to log at a time, to keep things from
363 // getting jumbled. Some other very uncommon logging operations (like
364 // changing the destination file for log messages of a given severity) also
365 // lock this mutex. Please be sure that anybody who might possibly need to
367 static Mutex log_mutex;
369 // Number of messages sent at each severity. Under log_mutex.
370 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
372 // Globally disable log writing (if disk is full)
373 static bool stop_writing = false;
375 const char*const LogSeverityNames[NUM_SEVERITIES] = {
376 "INFO", "WARNING", "ERROR", "FATAL"
379 // Has the user called SetExitOnDFatal(true)?
380 static bool exit_on_dfatal = true;
382 const char* GetLogSeverityName(LogSeverity severity) {
383 return LogSeverityNames[severity];
386 static bool SendEmailInternal(const char*dest, const char *subject,
387 const char*body, bool use_logging);
389 base::Logger::~Logger() {
394 // Encapsulates all file-system related state
395 class LogFileObject : public base::Logger {
397 LogFileObject(LogSeverity severity, const char* base_filename);
400 virtual void Write(bool force_flush, // Should we force a flush here?
401 time_t timestamp, // Timestamp for this entry
405 // Configuration options
406 void SetBasename(const char* basename);
407 void SetExtension(const char* ext);
408 void SetSymlinkBasename(const char* symlink_basename);
410 // Normal flushing routine
411 virtual void Flush();
413 // It is the actual file length for the system loggers,
414 // i.e., INFO, ERROR, etc.
415 virtual uint32 LogSize() {
420 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
421 // can avoid grabbing a lock. Usually Flush() calls it after
423 void FlushUnlocked();
426 static const uint32 kRolloverAttemptFrequency = 0x20;
429 bool base_filename_selected_;
430 string base_filename_;
431 string symlink_basename_;
432 string filename_extension_; // option users can specify (eg to add port#)
434 LogSeverity severity_;
435 uint32 bytes_since_flush_;
436 uint32 dropped_mem_length_;
438 unsigned int rollover_attempt_;
439 int64 next_flush_time_; // cycle count at which to flush log
441 // Actually create a logfile using the value of base_filename_ and the
442 // supplied argument time_pid_string
443 // REQUIRES: lock_ is held
444 bool CreateLogfile(const string& time_pid_string);
449 class LogDestination {
451 friend class LogMessage;
452 friend void ReprintFatalMessage();
453 friend base::Logger* base::GetLogger(LogSeverity);
454 friend void base::SetLogger(LogSeverity, base::Logger*);
456 // These methods are just forwarded to by their global versions.
457 static void SetLogDestination(LogSeverity severity,
458 const char* base_filename);
459 static void SetLogSymlink(LogSeverity severity,
460 const char* symlink_basename);
461 static void AddLogSink(LogSink *destination);
462 static void RemoveLogSink(LogSink *destination);
463 static void SetLogFilenameExtension(const char* filename_extension);
464 static void SetStderrLogging(LogSeverity min_severity);
465 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
466 static void LogToStderr();
467 // Flush all log files that are at least at the given severity level
468 static void FlushLogFiles(int min_severity);
469 static void FlushLogFilesUnsafe(int min_severity);
471 // we set the maximum size of our packet to be 1400, the logic being
472 // to prevent fragmentation.
473 // Really this number is arbitrary.
474 static const int kNetworkBytes = 1400;
476 static const string& hostname();
477 static const bool& terminal_supports_color() {
478 return terminal_supports_color_;
481 static void DeleteLogDestinations();
484 LogDestination(LogSeverity severity, const char* base_filename);
485 ~LogDestination() { }
487 // Take a log message of a particular severity and log it to stderr
488 // iff it's of a high enough severity to deserve it.
489 static void MaybeLogToStderr(LogSeverity severity, const char* message,
492 // Take a log message of a particular severity and log it to email
493 // iff it's of a high enough severity to deserve it.
494 static void MaybeLogToEmail(LogSeverity severity, const char* message,
496 // Take a log message of a particular severity and log it to a file
497 // iff the base filename is not "" (which means "don't log to me")
498 static void MaybeLogToLogfile(LogSeverity severity,
500 const char* message, size_t len);
501 // Take a log message of a particular severity and log it to the file
502 // for that severity and also for all files with severity less than
504 static void LogToAllLogfiles(LogSeverity severity,
506 const char* message, size_t len);
508 // Send logging info to all registered sinks.
509 static void LogToSinks(LogSeverity severity,
510 const char *full_filename,
511 const char *base_filename,
513 const struct ::tm* tm_time,
517 // Wait for all registered sinks via WaitTillSent
518 // including the optional one in "data".
519 static void WaitForSinks(LogMessage::LogMessageData* data);
521 static LogDestination* log_destination(LogSeverity severity);
523 LogFileObject fileobject_;
524 base::Logger* logger_; // Either &fileobject_, or wrapper around it
526 static LogDestination* log_destinations_[NUM_SEVERITIES];
527 static LogSeverity email_logging_severity_;
528 static string addresses_;
529 static string hostname_;
530 static bool terminal_supports_color_;
532 // arbitrary global logging destinations.
533 static vector<LogSink*>* sinks_;
535 // Protects the vector sinks_,
536 // but not the LogSink objects its elements reference.
537 static Mutex sink_mutex_;
540 LogDestination(const LogDestination&);
541 LogDestination& operator=(const LogDestination&);
544 // Errors do not get logged to email by default.
545 LogSeverity LogDestination::email_logging_severity_ = 99999;
547 string LogDestination::addresses_;
548 string LogDestination::hostname_;
550 vector<LogSink*>* LogDestination::sinks_ = NULL;
551 Mutex LogDestination::sink_mutex_;
552 bool LogDestination::terminal_supports_color_ = TerminalSupportsColor();
555 const string& LogDestination::hostname() {
556 if (hostname_.empty()) {
557 GetHostName(&hostname_);
558 if (hostname_.empty()) {
559 hostname_ = "(unknown)";
565 LogDestination::LogDestination(LogSeverity severity,
566 const char* base_filename)
567 : fileobject_(severity, base_filename),
568 logger_(&fileobject_) {
571 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
572 // assume we have the log_mutex or we simply don't care
574 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
575 LogDestination* log = log_destinations_[i];
577 // Flush the base fileobject_ logger directly instead of going
578 // through any wrappers to reduce chance of deadlock.
579 log->fileobject_.FlushUnlocked();
584 inline void LogDestination::FlushLogFiles(int min_severity) {
585 // Prevent any subtle race conditions by wrapping a mutex lock around
587 MutexLock l(&log_mutex);
588 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
589 LogDestination* log = log_destination(i);
591 log->logger_->Flush();
596 inline void LogDestination::SetLogDestination(LogSeverity severity,
597 const char* base_filename) {
598 assert(severity >= 0 && severity < NUM_SEVERITIES);
599 // Prevent any subtle race conditions by wrapping a mutex lock around
601 MutexLock l(&log_mutex);
602 log_destination(severity)->fileobject_.SetBasename(base_filename);
605 inline void LogDestination::SetLogSymlink(LogSeverity severity,
606 const char* symlink_basename) {
607 CHECK_GE(severity, 0);
608 CHECK_LT(severity, NUM_SEVERITIES);
609 MutexLock l(&log_mutex);
610 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
613 inline void LogDestination::AddLogSink(LogSink *destination) {
614 // Prevent any subtle race conditions by wrapping a mutex lock around
616 MutexLock l(&sink_mutex_);
617 if (!sinks_) sinks_ = new vector<LogSink*>;
618 sinks_->push_back(destination);
621 inline void LogDestination::RemoveLogSink(LogSink *destination) {
622 // Prevent any subtle race conditions by wrapping a mutex lock around
624 MutexLock l(&sink_mutex_);
625 // This doesn't keep the sinks in order, but who cares?
627 for (int i = sinks_->size() - 1; i >= 0; i--) {
628 if ((*sinks_)[i] == destination) {
629 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
637 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
638 // Prevent any subtle race conditions by wrapping a mutex lock around
640 MutexLock l(&log_mutex);
641 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
642 log_destination(severity)->fileobject_.SetExtension(ext);
646 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
647 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
648 // Prevent any subtle race conditions by wrapping a mutex lock around
650 MutexLock l(&log_mutex);
651 FLAGS_stderrthreshold = min_severity;
654 inline void LogDestination::LogToStderr() {
655 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
656 // SetLogDestination already do the locking!
657 SetStderrLogging(0); // thus everything is "also" logged to stderr
658 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
659 SetLogDestination(i, ""); // "" turns off logging to a logfile
663 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
664 const char* addresses) {
665 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
666 // Prevent any subtle race conditions by wrapping a mutex lock around
668 MutexLock l(&log_mutex);
669 LogDestination::email_logging_severity_ = min_severity;
670 LogDestination::addresses_ = addresses;
673 static void ColoredWriteToStderr(LogSeverity severity,
674 const char* message, size_t len) {
675 const GLogColor color =
676 (LogDestination::terminal_supports_color() && FLAGS_colorlogtostderr) ?
677 SeverityToColor(severity) : COLOR_DEFAULT;
679 // Avoid using cerr from this module since we may get called during
680 // exit code, and cerr may be partially or fully destroyed by then.
681 if (COLOR_DEFAULT == color) {
682 fwrite(message, len, 1, stderr);
686 const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
688 // Gets the current text color.
689 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
690 GetConsoleScreenBufferInfo(stderr_handle, &buffer_info);
691 const WORD old_color_attrs = buffer_info.wAttributes;
693 // We need to flush the stream buffers into the console before each
694 // SetConsoleTextAttribute call lest it affect the text that is already
695 // printed but has not yet reached the console.
697 SetConsoleTextAttribute(stderr_handle,
698 GetColorAttribute(color) | FOREGROUND_INTENSITY);
699 fwrite(message, len, 1, stderr);
701 // Restores the text color.
702 SetConsoleTextAttribute(stderr_handle, old_color_attrs);
704 fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color));
705 fwrite(message, len, 1, stderr);
706 fprintf(stderr, "\033[m"); // Resets the terminal to default.
710 static void WriteToStderr(const char* message, size_t len) {
711 // Avoid using cerr from this module since we may get called during
712 // exit code, and cerr may be partially or fully destroyed by then.
713 fwrite(message, len, 1, stderr);
716 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
717 const char* message, size_t len) {
718 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
719 ColoredWriteToStderr(severity, message, len);
721 // On Windows, also output to the debugger
722 ::OutputDebugStringA(string(message,len).c_str());
728 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
729 const char* message, size_t len) {
730 if (severity >= email_logging_severity_ ||
731 severity >= FLAGS_logemaillevel) {
732 string to(FLAGS_alsologtoemail);
733 if (!addresses_.empty()) {
739 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
740 glog_internal_namespace_::ProgramInvocationShortName());
741 string body(hostname());
743 body.append(message, len);
745 // should NOT use SendEmail(). The caller of this function holds the
746 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
747 // acquire the log_mutex object. Use SendEmailInternal() and set
748 // use_logging to false.
749 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
754 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
758 const bool should_flush = severity > FLAGS_logbuflevel;
759 LogDestination* destination = log_destination(severity);
760 destination->logger_->Write(should_flush, timestamp, message, len);
763 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
768 if ( FLAGS_logtostderr ) { // global flag: never log to file
769 ColoredWriteToStderr(severity, message, len);
771 for (int i = severity; i >= 0; --i)
772 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
776 inline void LogDestination::LogToSinks(LogSeverity severity,
777 const char *full_filename,
778 const char *base_filename,
780 const struct ::tm* tm_time,
782 size_t message_len) {
783 ReaderMutexLock l(&sink_mutex_);
785 for (int i = sinks_->size() - 1; i >= 0; i--) {
786 (*sinks_)[i]->send(severity, full_filename, base_filename,
787 line, tm_time, message, message_len);
792 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
793 ReaderMutexLock l(&sink_mutex_);
795 for (int i = sinks_->size() - 1; i >= 0; i--) {
796 (*sinks_)[i]->WaitTillSent();
799 const bool send_to_sink =
800 (data->send_method_ == &LogMessage::SendToSink) ||
801 (data->send_method_ == &LogMessage::SendToSinkAndLog);
802 if (send_to_sink && data->sink_ != NULL) {
803 data->sink_->WaitTillSent();
807 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
809 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
810 assert(severity >=0 && severity < NUM_SEVERITIES);
811 if (!log_destinations_[severity]) {
812 log_destinations_[severity] = new LogDestination(severity, NULL);
814 return log_destinations_[severity];
817 void LogDestination::DeleteLogDestinations() {
818 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
819 delete log_destinations_[severity];
820 log_destinations_[severity] = NULL;
822 MutexLock l(&sink_mutex_);
829 LogFileObject::LogFileObject(LogSeverity severity,
830 const char* base_filename)
831 : base_filename_selected_(base_filename != NULL),
832 base_filename_((base_filename != NULL) ? base_filename : ""),
833 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
834 filename_extension_(),
837 bytes_since_flush_(0),
838 dropped_mem_length_(0),
840 rollover_attempt_(kRolloverAttemptFrequency-1),
841 next_flush_time_(0) {
842 assert(severity >= 0);
843 assert(severity < NUM_SEVERITIES);
846 LogFileObject::~LogFileObject() {
854 void LogFileObject::SetBasename(const char* basename) {
856 base_filename_selected_ = true;
857 if (base_filename_ != basename) {
858 // Get rid of old log file since we are changing names
862 rollover_attempt_ = kRolloverAttemptFrequency-1;
864 base_filename_ = basename;
868 void LogFileObject::SetExtension(const char* ext) {
870 if (filename_extension_ != ext) {
871 // Get rid of old log file since we are changing names
875 rollover_attempt_ = kRolloverAttemptFrequency-1;
877 filename_extension_ = ext;
881 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
883 symlink_basename_ = symlink_basename;
886 void LogFileObject::Flush() {
891 void LogFileObject::FlushUnlocked(){
894 bytes_since_flush_ = 0;
896 // Figure out when we are due for another flush.
897 const int64 next = (FLAGS_logbufsecs
898 * static_cast<int64>(1000000)); // in usec
899 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
902 bool LogFileObject::CreateLogfile(const string& time_pid_string) {
903 string string_filename = base_filename_+filename_extension_+
905 const char* filename = string_filename.c_str();
906 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, FLAGS_logfile_mode);
907 if (fd == -1) return false;
909 // Mark the file close-on-exec. We don't really care if this fails
910 fcntl(fd, F_SETFD, FD_CLOEXEC);
913 file_ = fdopen(fd, "a"); // Make a FILE*.
914 if (file_ == NULL) { // Man, we're screwed!
916 unlink(filename); // Erase the half-baked evidence: an unusable log file
920 // We try to create a symlink called <program_name>.<severity>,
921 // which is easier to use. (Every time we create a new logfile,
922 // we destroy the old symlink and create a new one, so it always
923 // points to the latest logfile.) If it fails, we're sad but it's
925 if (!symlink_basename_.empty()) {
926 // take directory from filename
927 const char* slash = strrchr(filename, PATH_SEPARATOR);
928 const string linkname =
929 symlink_basename_ + '.' + LogSeverityNames[severity_];
931 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
932 linkpath += linkname;
933 unlink(linkpath.c_str()); // delete old one if it exists
935 #if defined(OS_WINDOWS)
936 // TODO(hamaji): Create lnk file on Windows?
937 #elif defined(HAVE_UNISTD_H)
938 // We must have unistd.h.
939 // Make the symlink be relative (in the same dir) so that if the
940 // entire log directory gets relocated the link is still valid.
941 const char *linkdest = slash ? (slash + 1) : filename;
942 if (symlink(linkdest, linkpath.c_str()) != 0) {
943 // silently ignore failures
946 // Make an additional link to the log file in a place specified by
947 // FLAGS_log_link, if indicated
948 if (!FLAGS_log_link.empty()) {
949 linkpath = FLAGS_log_link + "/" + linkname;
950 unlink(linkpath.c_str()); // delete old one if it exists
951 if (symlink(filename, linkpath.c_str()) != 0) {
952 // silently ignore failures
958 return true; // Everything worked
961 void LogFileObject::Write(bool force_flush,
967 // We don't log if the base_name_ is "" (which means "don't write")
968 if (base_filename_selected_ && base_filename_.empty()) {
972 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
974 if (file_ != NULL) fclose(file_);
976 file_length_ = bytes_since_flush_ = dropped_mem_length_ = 0;
977 rollover_attempt_ = kRolloverAttemptFrequency-1;
980 // If there's no destination file, make one before outputting
982 // Try to rollover the log file every 32 log messages. The only time
983 // this could matter would be when we have trouble creating the log
984 // file. If that happens, we'll lose lots of log messages, of course!
985 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
986 rollover_attempt_ = 0;
989 localtime_r(×tamp, &tm_time);
991 // The logfile's filename will have the date/time & pid in it
992 ostringstream time_pid_stream;
993 time_pid_stream.fill('0');
994 time_pid_stream << 1900+tm_time.tm_year
995 << setw(2) << 1+tm_time.tm_mon
996 << setw(2) << tm_time.tm_mday
998 << setw(2) << tm_time.tm_hour
999 << setw(2) << tm_time.tm_min
1000 << setw(2) << tm_time.tm_sec
1002 << GetMainThreadPid();
1003 const string& time_pid_string = time_pid_stream.str();
1005 if (base_filename_selected_) {
1006 if (!CreateLogfile(time_pid_string)) {
1007 perror("Could not create log file");
1008 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
1009 time_pid_string.c_str());
1013 // If no base filename for logs of this severity has been set, use a
1014 // default base filename of
1015 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
1016 // logfiles will have names like
1017 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
1018 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
1019 // and 4354 is the pid of the logging process. The date & time reflect
1020 // when the file was created for output.
1022 // Where does the file get put? Successively try the directories
1024 string stripped_filename(
1025 glog_internal_namespace_::ProgramInvocationShortName());
1027 GetHostName(&hostname);
1029 string uidname = MyUserName();
1030 // We should not call CHECK() here because this function can be
1031 // called after holding on to log_mutex. We don't want to
1032 // attempt to hold on to the same mutex, and get into a
1033 // deadlock. Simply use a name like invalid-user.
1034 if (uidname.empty()) uidname = "invalid-user";
1036 stripped_filename = stripped_filename+'.'+hostname+'.'
1038 +LogSeverityNames[severity_]+'.';
1039 // We're going to (potentially) try to put logs in several different dirs
1040 const vector<string> & log_dirs = GetLoggingDirectories();
1042 // Go through the list of dirs, and try to create the log file in each
1043 // until we succeed or run out of options
1044 bool success = false;
1045 for (vector<string>::const_iterator dir = log_dirs.begin();
1046 dir != log_dirs.end();
1048 base_filename_ = *dir + "/" + stripped_filename;
1049 if ( CreateLogfile(time_pid_string) ) {
1054 // If we never succeeded, we have to give up
1055 if ( success == false ) {
1056 perror("Could not create logging file");
1057 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
1058 time_pid_string.c_str());
1063 // Write a header message into the log file
1064 ostringstream file_header_stream;
1065 file_header_stream.fill('0');
1066 file_header_stream << "Log file created at: "
1067 << 1900+tm_time.tm_year << '/'
1068 << setw(2) << 1+tm_time.tm_mon << '/'
1069 << setw(2) << tm_time.tm_mday
1071 << setw(2) << tm_time.tm_hour << ':'
1072 << setw(2) << tm_time.tm_min << ':'
1073 << setw(2) << tm_time.tm_sec << '\n'
1074 << "Running on machine: "
1075 << LogDestination::hostname() << '\n'
1076 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
1077 << "threadid file:line] msg" << '\n';
1078 const string& file_header_string = file_header_stream.str();
1080 const int header_len = file_header_string.size();
1081 fwrite(file_header_string.data(), 1, header_len, file_);
1082 file_length_ += header_len;
1083 bytes_since_flush_ += header_len;
1086 // Write to LOG file
1087 if ( !stop_writing ) {
1088 // fwrite() doesn't return an error when the disk is full, for
1089 // messages that are less than 4096 bytes. When the disk is full,
1090 // it returns the message length for messages that are less than
1091 // 4096 bytes. fwrite() returns 4096 for message lengths that are
1092 // greater than 4096, thereby indicating an error.
1094 fwrite(message, 1, message_len, file_);
1095 if ( FLAGS_stop_logging_if_full_disk &&
1096 errno == ENOSPC ) { // disk full, stop writing to disk
1097 stop_writing = true; // until the disk is
1100 file_length_ += message_len;
1101 bytes_since_flush_ += message_len;
1104 if ( CycleClock_Now() >= next_flush_time_ )
1105 stop_writing = false; // check to see if disk has free space.
1106 return; // no need to flush
1109 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
1110 // or every "FLAGS_logbufsecs" seconds.
1112 (bytes_since_flush_ >= 1000000) ||
1113 (CycleClock_Now() >= next_flush_time_) ) {
1116 // Only consider files >= 3MiB
1117 if (FLAGS_drop_log_memory && file_length_ >= (3 << 20)) {
1118 // Don't evict the most recent 1-2MiB so as not to impact a tailer
1119 // of the log file and to avoid page rounding issue on linux < 4.7
1120 uint32 total_drop_length = (file_length_ & ~((1 << 20) - 1)) - (1 << 20);
1121 uint32 this_drop_length = total_drop_length - dropped_mem_length_;
1122 if (this_drop_length >= (2 << 20)) {
1123 // Only advise when >= 2MiB to drop
1124 posix_fadvise(fileno(file_), dropped_mem_length_, this_drop_length,
1125 POSIX_FADV_DONTNEED);
1126 dropped_mem_length_ = total_drop_length;
1136 // Static log data space to avoid alloc failures in a LOG(FATAL)
1138 // Since multiple threads may call LOG(FATAL), and we want to preserve
1139 // the data from the first call, we allocate two sets of space. One
1140 // for exclusive use by the first thread, and one for shared use by
1141 // all other threads.
1142 static Mutex fatal_msg_lock;
1143 static CrashReason crash_reason;
1144 static bool fatal_msg_exclusive = true;
1145 static LogMessage::LogMessageData fatal_msg_data_exclusive;
1146 static LogMessage::LogMessageData fatal_msg_data_shared;
1148 LogMessage::LogMessageData::LogMessageData()
1149 : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) {
1152 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1153 int ctr, void (LogMessage::*send_method)())
1154 : allocated_(NULL) {
1155 Init(file, line, severity, send_method);
1156 data_->stream_.set_ctr(ctr);
1159 LogMessage::LogMessage(const char* file, int line,
1160 const CheckOpString& result)
1161 : allocated_(NULL) {
1162 Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
1163 stream() << "Check failed: " << (*result.str_) << " ";
1166 LogMessage::LogMessage(const char* file, int line)
1167 : allocated_(NULL) {
1168 Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
1171 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
1172 : allocated_(NULL) {
1173 Init(file, line, severity, &LogMessage::SendToLog);
1176 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1177 LogSink* sink, bool also_send_to_log)
1178 : allocated_(NULL) {
1179 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
1180 &LogMessage::SendToSink);
1181 data_->sink_ = sink; // override Init()'s setting to NULL
1184 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1185 vector<string> *outvec)
1186 : allocated_(NULL) {
1187 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
1188 data_->outvec_ = outvec; // override Init()'s setting to NULL
1191 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1193 : allocated_(NULL) {
1194 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
1195 data_->message_ = message; // override Init()'s setting to NULL
1198 void LogMessage::Init(const char* file,
1200 LogSeverity severity,
1201 void (LogMessage::*send_method)()) {
1203 if (severity != GLOG_FATAL || !exit_on_dfatal) {
1204 allocated_ = new LogMessageData();
1206 data_->first_fatal_ = false;
1208 MutexLock l(&fatal_msg_lock);
1209 if (fatal_msg_exclusive) {
1210 fatal_msg_exclusive = false;
1211 data_ = &fatal_msg_data_exclusive;
1212 data_->first_fatal_ = true;
1214 data_ = &fatal_msg_data_shared;
1215 data_->first_fatal_ = false;
1220 data_->preserved_errno_ = errno;
1221 data_->severity_ = severity;
1222 data_->line_ = line;
1223 data_->send_method_ = send_method;
1224 data_->sink_ = NULL;
1225 data_->outvec_ = NULL;
1226 WallTime now = WallTime_Now();
1227 data_->timestamp_ = static_cast<time_t>(now);
1228 localtime_r(&data_->timestamp_, &data_->tm_time_);
1229 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1230 RawLog__SetLastTime(data_->tm_time_, usecs);
1232 data_->num_chars_to_log_ = 0;
1233 data_->num_chars_to_syslog_ = 0;
1234 data_->basename_ = const_basename(file);
1235 data_->fullname_ = file;
1236 data_->has_been_flushed_ = false;
1238 // If specified, prepend a prefix to each line. For example:
1239 // I1018 160715 f5d4fbb0 logging.cc:1153]
1240 // (log level, GMT month, date, time, thread_id, file basename, line)
1241 // We exclude the thread_id for the default thread.
1242 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1243 stream() << LogSeverityNames[severity][0]
1244 << setw(2) << 1+data_->tm_time_.tm_mon
1245 << setw(2) << data_->tm_time_.tm_mday
1247 << setw(2) << data_->tm_time_.tm_hour << ':'
1248 << setw(2) << data_->tm_time_.tm_min << ':'
1249 << setw(2) << data_->tm_time_.tm_sec << "."
1252 << setfill(' ') << setw(5)
1253 << static_cast<unsigned int>(GetTID()) << setfill('0')
1255 << data_->basename_ << ':' << data_->line_ << "] ";
1257 data_->num_prefix_chars_ = data_->stream_.pcount();
1259 if (!FLAGS_log_backtrace_at.empty()) {
1261 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1262 #ifdef HAVE_STACKTRACE
1263 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1265 DumpStackTraceToString(&stacktrace);
1266 stream() << " (stacktrace:\n" << stacktrace << ") ";
1272 LogMessage::~LogMessage() {
1277 int LogMessage::preserved_errno() const {
1278 return data_->preserved_errno_;
1281 ostream& LogMessage::stream() {
1282 return data_->stream_;
1285 // Flush buffered message, called by the destructor, or any other function
1286 // that needs to synchronize the log.
1287 void LogMessage::Flush() {
1288 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1291 data_->num_chars_to_log_ = data_->stream_.pcount();
1292 data_->num_chars_to_syslog_ =
1293 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1295 // Do we need to add a \n to the end of this message?
1296 bool append_newline =
1297 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1298 char original_final_char = '\0';
1300 // If we do need to add a \n, we'll do it by violating the memory of the
1301 // ostrstream buffer. This is quick, and we'll make sure to undo our
1302 // modification before anything else is done with the ostrstream. It
1303 // would be preferable not to do things this way, but it seems to be
1304 // the best way to deal with this.
1305 if (append_newline) {
1306 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1307 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1310 // Prevent any subtle race conditions by wrapping a mutex lock around
1311 // the actual logging action per se.
1313 MutexLock l(&log_mutex);
1314 (this->*(data_->send_method_))();
1315 ++num_messages_[static_cast<int>(data_->severity_)];
1317 LogDestination::WaitForSinks(data_);
1319 if (append_newline) {
1320 // Fix the ostrstream back how it was before we screwed with it.
1321 // It's 99.44% certain that we don't need to worry about doing this.
1322 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1325 // If errno was already set before we enter the logging call, we'll
1326 // set it back to that value when we return from the logging call.
1327 // It happens often that we log an error message after a syscall
1328 // failure, which can potentially set the errno to some other
1329 // values. We would like to preserve the original errno.
1330 if (data_->preserved_errno_ != 0) {
1331 errno = data_->preserved_errno_;
1334 // Note that this message is now safely logged. If we're asked to flush
1335 // again, as a result of destruction, say, we'll do nothing on future calls.
1336 data_->has_been_flushed_ = true;
1339 // Copy of first FATAL log message so that we can print it out again
1340 // after all the stack traces. To preserve legacy behavior, we don't
1341 // use fatal_msg_data_exclusive.
1342 static time_t fatal_time;
1343 static char fatal_message[256];
1345 void ReprintFatalMessage() {
1346 if (fatal_message[0]) {
1347 const int n = strlen(fatal_message);
1348 if (!FLAGS_logtostderr) {
1349 // Also write to stderr (don't color to avoid terminal checks)
1350 WriteToStderr(fatal_message, n);
1352 LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1356 // L >= log_mutex (callers must hold the log_mutex).
1357 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1358 static bool already_warned_before_initgoogle = false;
1360 log_mutex.AssertHeld();
1362 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1363 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1365 // Messages of a given severity get logged to lower severity logs, too
1367 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1368 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1369 "written to STDERR\n";
1370 WriteToStderr(w, strlen(w));
1371 already_warned_before_initgoogle = true;
1374 // global flag: never log to file if set. Also -- don't log to a
1375 // file if we haven't parsed the command line flags to get the
1377 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1378 ColoredWriteToStderr(data_->severity_,
1379 data_->message_text_, data_->num_chars_to_log_);
1381 // this could be protected by a flag if necessary.
1382 LogDestination::LogToSinks(data_->severity_,
1383 data_->fullname_, data_->basename_,
1384 data_->line_, &data_->tm_time_,
1385 data_->message_text_ + data_->num_prefix_chars_,
1386 (data_->num_chars_to_log_ -
1387 data_->num_prefix_chars_ - 1));
1390 // log this message to all log files of severity <= severity_
1391 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1392 data_->message_text_,
1393 data_->num_chars_to_log_);
1395 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1396 data_->num_chars_to_log_);
1397 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1398 data_->num_chars_to_log_);
1399 LogDestination::LogToSinks(data_->severity_,
1400 data_->fullname_, data_->basename_,
1401 data_->line_, &data_->tm_time_,
1402 data_->message_text_ + data_->num_prefix_chars_,
1403 (data_->num_chars_to_log_
1404 - data_->num_prefix_chars_ - 1));
1405 // NOTE: -1 removes trailing \n
1408 // If we log a FATAL message, flush all the log destinations, then toss
1409 // a signal for others to catch. We leave the logs in a state that
1410 // someone else can use them (as long as they flush afterwards)
1411 if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1412 if (data_->first_fatal_) {
1413 // Store crash information so that it is accessible from within signal
1414 // handlers that may be invoked later.
1415 RecordCrashReason(&crash_reason);
1416 SetCrashReason(&crash_reason);
1418 // Store shortened fatal message for other logs and GWQ status
1419 const int copy = min<int>(data_->num_chars_to_log_,
1420 sizeof(fatal_message)-1);
1421 memcpy(fatal_message, data_->message_text_, copy);
1422 fatal_message[copy] = '\0';
1423 fatal_time = data_->timestamp_;
1426 if (!FLAGS_logtostderr) {
1427 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1428 if ( LogDestination::log_destinations_[i] )
1429 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1433 // release the lock that our caller (directly or indirectly)
1434 // LogMessage::~LogMessage() grabbed so that signal handlers
1435 // can use the logging facility. Alternately, we could add
1436 // an entire unsafe logging interface to bypass locking
1437 // for signal handlers but this seems simpler.
1439 LogDestination::WaitForSinks(data_);
1441 const char* message = "*** Check failure stack trace: ***\n";
1442 if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1449 void LogMessage::RecordCrashReason(
1450 glog_internal_namespace_::CrashReason* reason) {
1451 reason->filename = fatal_msg_data_exclusive.fullname_;
1452 reason->line_number = fatal_msg_data_exclusive.line_;
1453 reason->message = fatal_msg_data_exclusive.message_text_ +
1454 fatal_msg_data_exclusive.num_prefix_chars_;
1455 #ifdef HAVE_STACKTRACE
1456 // Retrieve the stack trace, omitting the logging frames that got us here.
1457 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1463 #ifdef HAVE___ATTRIBUTE__
1464 # define ATTRIBUTE_NORETURN __attribute__((noreturn))
1466 # define ATTRIBUTE_NORETURN
1469 static void logging_fail() ATTRIBUTE_NORETURN;
1471 static void logging_fail() {
1472 #if defined(_DEBUG) && defined(_MSC_VER)
1473 // When debugging on windows, avoid the obnoxious dialog and make
1474 // it possible to continue past a LOG(FATAL) in the debugger
1481 typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN;
1483 GOOGLE_GLOG_DLL_DECL
1484 logging_fail_func_t g_logging_fail_func = &logging_fail;
1486 void InstallFailureFunction(void (*fail_func)()) {
1487 g_logging_fail_func = (logging_fail_func_t)fail_func;
1490 void LogMessage::Fail() {
1491 g_logging_fail_func();
1494 // L >= log_mutex (callers must hold the log_mutex).
1495 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1496 if (data_->sink_ != NULL) {
1497 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1498 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1499 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1500 data_->line_, &data_->tm_time_,
1501 data_->message_text_ + data_->num_prefix_chars_,
1502 (data_->num_chars_to_log_ -
1503 data_->num_prefix_chars_ - 1));
1507 // L >= log_mutex (callers must hold the log_mutex).
1508 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1513 // L >= log_mutex (callers must hold the log_mutex).
1514 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1515 if (data_->outvec_ != NULL) {
1516 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1517 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1518 // Omit prefix of message and trailing newline when recording in outvec_.
1519 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1520 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1521 data_->outvec_->push_back(string(start, len));
1527 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1528 if (data_->message_ != NULL) {
1529 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1530 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1531 // Omit prefix of message and trailing newline when writing to message_.
1532 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1533 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1534 data_->message_->assign(start, len);
1539 // L >= log_mutex (callers must hold the log_mutex).
1540 void LogMessage::SendToSyslogAndLog() {
1541 #ifdef HAVE_SYSLOG_H
1542 // Before any calls to syslog(), make a single call to openlog()
1543 static bool openlog_already_called = false;
1544 if (!openlog_already_called) {
1545 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1546 LOG_CONS | LOG_NDELAY | LOG_PID,
1548 openlog_already_called = true;
1551 // This array maps Google severity levels to syslog levels
1552 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1553 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1554 int(data_->num_chars_to_syslog_),
1555 data_->message_text_ + data_->num_prefix_chars_);
1558 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1562 base::Logger* base::GetLogger(LogSeverity severity) {
1563 MutexLock l(&log_mutex);
1564 return LogDestination::log_destination(severity)->logger_;
1567 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1568 MutexLock l(&log_mutex);
1569 LogDestination::log_destination(severity)->logger_ = logger;
1572 // L < log_mutex. Acquires and releases mutex_.
1573 int64 LogMessage::num_messages(int severity) {
1574 MutexLock l(&log_mutex);
1575 return num_messages_[severity];
1578 // Output the COUNTER value. This is only valid if ostream is a
1580 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1582 LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
1584 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1586 CHECK(log && log == log->self())
1587 << "You must not use COUNTER with non-glog ostream";
1592 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1593 LogSeverity severity, int ctr,
1594 void (LogMessage::*send_method)())
1595 : LogMessage(file, line, severity, ctr, send_method) {
1598 ErrnoLogMessage::~ErrnoLogMessage() {
1599 // Don't access errno directly because it may have been altered
1600 // while streaming the message.
1601 stream() << ": " << StrError(preserved_errno()) << " ["
1602 << preserved_errno() << "]";
1605 void FlushLogFiles(LogSeverity min_severity) {
1606 LogDestination::FlushLogFiles(min_severity);
1609 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1610 LogDestination::FlushLogFilesUnsafe(min_severity);
1613 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1614 LogDestination::SetLogDestination(severity, base_filename);
1617 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1618 LogDestination::SetLogSymlink(severity, symlink_basename);
1621 LogSink::~LogSink() {
1624 void LogSink::WaitTillSent() {
1628 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1629 const struct ::tm* tm_time,
1630 const char* message, size_t message_len) {
1631 ostringstream stream(string(message, message_len));
1634 // FIXME(jrvb): Updating this to use the correct value for usecs
1635 // requires changing the signature for both this method and
1636 // LogSink::send(). This change needs to be done in a separate CL
1637 // so subclasses of LogSink can be updated at the same time.
1640 stream << LogSeverityNames[severity][0]
1641 << setw(2) << 1+tm_time->tm_mon
1642 << setw(2) << tm_time->tm_mday
1644 << setw(2) << tm_time->tm_hour << ':'
1645 << setw(2) << tm_time->tm_min << ':'
1646 << setw(2) << tm_time->tm_sec << '.'
1649 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1651 << file << ':' << line << "] ";
1653 stream << string(message, message_len);
1654 return stream.str();
1657 void AddLogSink(LogSink *destination) {
1658 LogDestination::AddLogSink(destination);
1661 void RemoveLogSink(LogSink *destination) {
1662 LogDestination::RemoveLogSink(destination);
1665 void SetLogFilenameExtension(const char* ext) {
1666 LogDestination::SetLogFilenameExtension(ext);
1669 void SetStderrLogging(LogSeverity min_severity) {
1670 LogDestination::SetStderrLogging(min_severity);
1673 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1674 LogDestination::SetEmailLogging(min_severity, addresses);
1677 void LogToStderr() {
1678 LogDestination::LogToStderr();
1682 namespace internal {
1684 bool GetExitOnDFatal() {
1685 MutexLock l(&log_mutex);
1686 return exit_on_dfatal;
1689 // Determines whether we exit the program for a LOG(DFATAL) message in
1690 // debug mode. It does this by skipping the call to Fail/FailQuietly.
1691 // This is intended for testing only.
1693 // This can have some effects on LOG(FATAL) as well. Failure messages
1694 // are always allocated (rather than sharing a buffer), the crash
1695 // reason is not recorded, the "gwq" status message is not updated,
1696 // and the stack trace is not recorded. The LOG(FATAL) *will* still
1697 // exit the program. Since this function is used only in testing,
1698 // these differences are acceptable.
1699 void SetExitOnDFatal(bool value) {
1700 MutexLock l(&log_mutex);
1701 exit_on_dfatal = value;
1704 } // namespace internal
1707 // use_logging controls whether the logging functions LOG/VLOG are used
1708 // to log errors. It should be set to false when the caller holds the
1710 static bool SendEmailInternal(const char*dest, const char *subject,
1711 const char*body, bool use_logging) {
1712 if (dest && *dest) {
1713 if ( use_logging ) {
1714 VLOG(1) << "Trying to send TITLE:" << subject
1715 << " BODY:" << body << " to " << dest;
1717 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1718 subject, body, dest);
1722 FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1723 FILE* pipe = popen(cmd.c_str(), "w");
1725 // Add the body if we have one
1727 fwrite(body, sizeof(char), strlen(body), pipe);
1728 bool ok = pclose(pipe) != -1;
1730 if ( use_logging ) {
1731 LOG(ERROR) << "Problems sending mail to " << dest << ": "
1734 fprintf(stderr, "Problems sending mail to %s: %s\n",
1735 dest, StrError(errno).c_str());
1740 if ( use_logging ) {
1741 LOG(ERROR) << "Unable to send mail to " << dest;
1743 fprintf(stderr, "Unable to send mail to %s\n", dest);
1750 bool SendEmail(const char*dest, const char *subject, const char*body){
1751 return SendEmailInternal(dest, subject, body, true);
1754 static void GetTempDirectories(vector<string>* list) {
1757 // On windows we'll try to find a directory in this order:
1758 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1761 // C:/WINDOWS/ or C:/WINNT/
1764 if (GetTempPathA(MAX_PATH, tmp))
1765 list->push_back(tmp);
1766 list->push_back("C:\\tmp\\");
1767 list->push_back("C:\\temp\\");
1769 // Directories, in order of preference. If we find a dir that
1770 // exists, we stop adding other less-preferred dirs
1771 const char * candidates[] = {
1772 // Non-null only during unittest/regtest
1773 getenv("TEST_TMPDIR"),
1775 // Explicitly-supplied temp dirs
1776 getenv("TMPDIR"), getenv("TMP"),
1778 // If all else fails
1782 for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
1783 const char *d = candidates[i];
1784 if (!d) continue; // Empty env var
1786 // Make sure we don't surprise anyone who's expecting a '/'
1788 if (dstr[dstr.size() - 1] != '/') {
1791 list->push_back(dstr);
1793 struct stat statbuf;
1794 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1795 // We found a dir that exists - we're done.
1803 static vector<string>* logging_directories_list;
1805 const vector<string>& GetLoggingDirectories() {
1806 // Not strictly thread-safe but we're called early in InitGoogle().
1807 if (logging_directories_list == NULL) {
1808 logging_directories_list = new vector<string>;
1810 if ( !FLAGS_log_dir.empty() ) {
1811 // A dir was specified, we should use it
1812 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1814 GetTempDirectories(logging_directories_list);
1817 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1818 logging_directories_list->push_back(tmp);
1819 logging_directories_list->push_back(".\\");
1821 logging_directories_list->push_back("./");
1825 return *logging_directories_list;
1828 void TestOnly_ClearLoggingDirectoriesList() {
1829 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1830 "called from test code.\n");
1831 delete logging_directories_list;
1832 logging_directories_list = NULL;
1835 void GetExistingTempDirectories(vector<string>* list) {
1836 GetTempDirectories(list);
1837 vector<string>::iterator i_dir = list->begin();
1838 while( i_dir != list->end() ) {
1839 // zero arg to access means test for existence; no constant
1840 // defined on windows
1841 if ( access(i_dir->c_str(), 0) ) {
1842 i_dir = list->erase(i_dir);
1849 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1850 #ifdef HAVE_UNISTD_H
1851 struct stat statbuf;
1852 const int kCopyBlockSize = 8 << 10;
1853 char copybuf[kCopyBlockSize];
1854 int64 read_offset, write_offset;
1855 // Don't follow symlinks unless they're our own fd symlinks in /proc
1857 // TODO(hamaji): Support other environments.
1859 const char *procfd_prefix = "/proc/self/fd/";
1860 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1863 int fd = open(path, flags);
1865 if (errno == EFBIG) {
1866 // The log file in question has got too big for us to open. The
1867 // real fix for this would be to compile logging.cc (or probably
1868 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1870 // Instead just truncate the file to something we can manage
1871 if (truncate(path, 0) == -1) {
1872 PLOG(ERROR) << "Unable to truncate " << path;
1874 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1877 PLOG(ERROR) << "Unable to open " << path;
1882 if (fstat(fd, &statbuf) == -1) {
1883 PLOG(ERROR) << "Unable to fstat()";
1887 // See if the path refers to a regular file bigger than the
1889 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1890 if (statbuf.st_size <= limit) goto out_close_fd;
1891 if (statbuf.st_size <= keep) goto out_close_fd;
1893 // This log file is too large - we need to truncate it
1894 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1896 // Copy the last "keep" bytes of the file to the beginning of the file
1897 read_offset = statbuf.st_size - keep;
1899 int bytesin, bytesout;
1900 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1901 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1902 if (bytesout == -1) {
1903 PLOG(ERROR) << "Unable to write to " << path;
1905 } else if (bytesout != bytesin) {
1906 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1908 read_offset += bytesin;
1909 write_offset += bytesout;
1911 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1913 // Truncate the remainder of the file. If someone else writes to the
1914 // end of the file after our last read() above, we lose their latest
1915 // data. Too bad ...
1916 if (ftruncate(fd, write_offset) == -1) {
1917 PLOG(ERROR) << "Unable to truncate " << path;
1923 LOG(ERROR) << "No log truncation support.";
1927 void TruncateStdoutStderr() {
1928 #ifdef HAVE_UNISTD_H
1929 int64 limit = MaxLogSize() << 20;
1930 int64 keep = 1 << 20;
1931 TruncateLogFile("/proc/self/fd/1", limit, keep);
1932 TruncateLogFile("/proc/self/fd/2", limit, keep);
1934 LOG(ERROR) << "No log truncation support.";
1939 // Helper functions for string comparisons.
1940 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1941 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1942 const char* names) { \
1943 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1944 if (equal == expected) return NULL; \
1949 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1950 return new string(ss.str()); \
1953 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1954 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1955 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1956 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1957 #undef DEFINE_CHECK_STROP_IMPL
1959 int posix_strerror_r(int err, char *buf, size_t len) {
1960 // Sanity check input parameters
1961 if (buf == NULL || len <= 0) {
1966 // Reset buf and errno, and try calling whatever version of strerror_r()
1967 // is implemented by glibc
1969 int old_errno = errno;
1971 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1973 // Both versions set errno on failure
1975 // Should already be there, but better safe than sorry
1981 // POSIX is vague about whether the string will be terminated, although
1982 // is indirectly implies that typically ERANGE will be returned, instead
1983 // of truncating the string. This is different from the GNU implementation.
1984 // We play it safe by always terminating the string explicitly.
1985 buf[len-1] = '\000';
1987 // If the function succeeded, we can use its exit code to determine the
1988 // semantics implemented by glibc
1992 // GNU semantics detected
1997 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
1998 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
1999 // This means an error on MacOSX or FreeBSD.
2003 strncat(buf, rc, len-1);
2009 string StrError(int err) {
2011 int rc = posix_strerror_r(err, buf, sizeof(buf));
2012 if ((rc < 0) || (buf[0] == '\000')) {
2013 snprintf(buf, sizeof(buf), "Error number %d", err);
2018 LogMessageFatal::LogMessageFatal(const char* file, int line) :
2019 LogMessage(file, line, GLOG_FATAL) {}
2021 LogMessageFatal::LogMessageFatal(const char* file, int line,
2022 const CheckOpString& result) :
2023 LogMessage(file, line, result) {}
2025 LogMessageFatal::~LogMessageFatal() {
2032 CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
2033 : stream_(new ostringstream) {
2034 *stream_ << exprtext << " (";
2037 CheckOpMessageBuilder::~CheckOpMessageBuilder() {
2041 ostream* CheckOpMessageBuilder::ForVar2() {
2042 *stream_ << " vs. ";
2046 string* CheckOpMessageBuilder::NewString() {
2048 return new string(stream_->str());
2054 void MakeCheckOpValueString(std::ostream* os, const char& v) {
2055 if (v >= 32 && v <= 126) {
2056 (*os) << "'" << v << "'";
2058 (*os) << "char value " << (short)v;
2063 void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
2064 if (v >= 32 && v <= 126) {
2065 (*os) << "'" << v << "'";
2067 (*os) << "signed char value " << (short)v;
2072 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
2073 if (v >= 32 && v <= 126) {
2074 (*os) << "'" << v << "'";
2076 (*os) << "unsigned char value " << (unsigned short)v;
2080 void InitGoogleLogging(const char* argv0) {
2081 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
2084 void ShutdownGoogleLogging() {
2085 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
2086 LogDestination::DeleteLogDestinations();
2087 delete logging_directories_list;
2088 logging_directories_list = NULL;
2091 _END_GOOGLE_NAMESPACE_