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(colorlogtostderr, 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 '/'
183 static ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
184 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
185 if (orig_offset == (off_t)-1)
187 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
189 ssize_t len = read(fd, buf, count);
192 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
196 #endif // !HAVE_PREAD
199 static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) {
200 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
201 if (orig_offset == (off_t)-1)
203 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
205 ssize_t len = write(fd, buf, count);
208 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
212 #endif // !HAVE_PWRITE
214 static void GetHostName(string* hostname) {
215 #if defined(HAVE_SYS_UTSNAME_H)
217 if (0 != uname(&buf)) {
218 // ensure null termination on failure
219 *buf.nodename = '\0';
221 *hostname = buf.nodename;
222 #elif defined(OS_WINDOWS)
223 char buf[MAX_COMPUTERNAME_LENGTH + 1];
224 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
225 if (GetComputerNameA(buf, &len)) {
231 # warning There is no way to retrieve the host name.
232 *hostname = "(unknown)";
236 // Returns true iff terminal supports using colors in output.
237 static bool TerminalSupportsColor() {
238 bool term_supports_color = false;
240 // on Windows TERM variable is usually not set, but the console does
242 term_supports_color = true;
244 // On non-Windows platforms, we rely on the TERM variable.
245 const char* const term = getenv("TERM");
246 if (term != NULL && term[0] != '\0') {
247 term_supports_color =
248 !strcmp(term, "xterm") ||
249 !strcmp(term, "xterm-color") ||
250 !strcmp(term, "xterm-256color") ||
251 !strcmp(term, "screen") ||
252 !strcmp(term, "linux") ||
253 !strcmp(term, "cygwin");
256 return term_supports_color;
259 _START_GOOGLE_NAMESPACE_
268 static GLogColor SeverityToColor(LogSeverity severity) {
269 assert(severity >= 0 && severity < NUM_SEVERITIES);
270 GLogColor color = COLOR_DEFAULT;
273 color = COLOR_DEFAULT;
276 color = COLOR_YELLOW;
283 // should never get here.
291 // Returns the character attribute for the given color.
292 WORD GetColorAttribute(GLogColor color) {
294 case COLOR_RED: return FOREGROUND_RED;
295 case COLOR_GREEN: return FOREGROUND_GREEN;
296 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
303 // Returns the ANSI color code for the given color.
304 const char* GetAnsiColorCode(GLogColor color) {
306 case COLOR_RED: return "1";
307 case COLOR_GREEN: return "2";
308 case COLOR_YELLOW: return "3";
309 case COLOR_DEFAULT: return "";
311 return NULL; // stop warning about return type.
316 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
317 static int32 MaxLogSize() {
318 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
321 struct LogMessage::LogMessageData {
324 int preserved_errno_; // preserved errno
325 char* buf_; // buffer space for non FATAL messages
326 char* message_text_; // Complete message text (points to selected buffer)
327 LogStream* stream_alloc_;
329 char severity_; // What level is this LogMessage logged at?
330 int line_; // line number where logging call is.
331 void (LogMessage::*send_method_)(); // Call this in destructor to send
332 union { // At most one of these is used: union to keep the size low.
333 LogSink* sink_; // NULL or sink to send message to
334 std::vector<std::string>* outvec_; // NULL or vector to push message onto
335 std::string* message_; // NULL or string to write message into
337 time_t timestamp_; // Time of creation of LogMessage
338 struct ::tm tm_time_; // Time of creation of LogMessage
339 size_t num_prefix_chars_; // # of chars of prefix in this message
340 size_t num_chars_to_log_; // # of chars of msg to send to log
341 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
342 const char* basename_; // basename of file that called LOG
343 const char* fullname_; // fullname of file that called LOG
344 bool has_been_flushed_; // false => data has not been flushed
345 bool first_fatal_; // true => this was first fatal msg
350 LogMessageData(const LogMessageData&);
351 void operator=(const LogMessageData&);
354 // A mutex that allows only one thread to log at a time, to keep things from
355 // getting jumbled. Some other very uncommon logging operations (like
356 // changing the destination file for log messages of a given severity) also
357 // lock this mutex. Please be sure that anybody who might possibly need to
359 static Mutex log_mutex;
361 // Number of messages sent at each severity. Under log_mutex.
362 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
364 // Globally disable log writing (if disk is full)
365 static bool stop_writing = false;
367 const char*const LogSeverityNames[NUM_SEVERITIES] = {
368 "INFO", "WARNING", "ERROR", "FATAL"
371 // Has the user called SetExitOnDFatal(true)?
372 static bool exit_on_dfatal = true;
374 const char* GetLogSeverityName(LogSeverity severity) {
375 return LogSeverityNames[severity];
378 static bool SendEmailInternal(const char*dest, const char *subject,
379 const char*body, bool use_logging);
381 base::Logger::~Logger() {
386 // Encapsulates all file-system related state
387 class LogFileObject : public base::Logger {
389 LogFileObject(LogSeverity severity, const char* base_filename);
392 virtual void Write(bool force_flush, // Should we force a flush here?
393 time_t timestamp, // Timestamp for this entry
397 // Configuration options
398 void SetBasename(const char* basename);
399 void SetExtension(const char* ext);
400 void SetSymlinkBasename(const char* symlink_basename);
402 // Normal flushing routine
403 virtual void Flush();
405 // It is the actual file length for the system loggers,
406 // i.e., INFO, ERROR, etc.
407 virtual uint32 LogSize() {
412 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
413 // can avoid grabbing a lock. Usually Flush() calls it after
415 void FlushUnlocked();
418 static const uint32 kRolloverAttemptFrequency = 0x20;
421 bool base_filename_selected_;
422 string base_filename_;
423 string symlink_basename_;
424 string filename_extension_; // option users can specify (eg to add port#)
426 LogSeverity severity_;
427 uint32 bytes_since_flush_;
429 unsigned int rollover_attempt_;
430 int64 next_flush_time_; // cycle count at which to flush log
432 // Actually create a logfile using the value of base_filename_ and the
433 // supplied argument time_pid_string
434 // REQUIRES: lock_ is held
435 bool CreateLogfile(const string& time_pid_string);
440 class LogDestination {
442 friend class LogMessage;
443 friend void ReprintFatalMessage();
444 friend base::Logger* base::GetLogger(LogSeverity);
445 friend void base::SetLogger(LogSeverity, base::Logger*);
447 // These methods are just forwarded to by their global versions.
448 static void SetLogDestination(LogSeverity severity,
449 const char* base_filename);
450 static void SetLogSymlink(LogSeverity severity,
451 const char* symlink_basename);
452 static void AddLogSink(LogSink *destination);
453 static void RemoveLogSink(LogSink *destination);
454 static void SetLogFilenameExtension(const char* filename_extension);
455 static void SetStderrLogging(LogSeverity min_severity);
456 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
457 static void LogToStderr();
458 // Flush all log files that are at least at the given severity level
459 static void FlushLogFiles(int min_severity);
460 static void FlushLogFilesUnsafe(int min_severity);
462 // we set the maximum size of our packet to be 1400, the logic being
463 // to prevent fragmentation.
464 // Really this number is arbitrary.
465 static const int kNetworkBytes = 1400;
467 static const string& hostname();
468 static const bool& terminal_supports_color() {
469 return terminal_supports_color_;
472 static void DeleteLogDestinations();
475 LogDestination(LogSeverity severity, const char* base_filename);
476 ~LogDestination() { }
478 // Take a log message of a particular severity and log it to stderr
479 // iff it's of a high enough severity to deserve it.
480 static void MaybeLogToStderr(LogSeverity severity, const char* message,
483 // Take a log message of a particular severity and log it to email
484 // iff it's of a high enough severity to deserve it.
485 static void MaybeLogToEmail(LogSeverity severity, const char* message,
487 // Take a log message of a particular severity and log it to a file
488 // iff the base filename is not "" (which means "don't log to me")
489 static void MaybeLogToLogfile(LogSeverity severity,
491 const char* message, size_t len);
492 // Take a log message of a particular severity and log it to the file
493 // for that severity and also for all files with severity less than
495 static void LogToAllLogfiles(LogSeverity severity,
497 const char* message, size_t len);
499 // Send logging info to all registered sinks.
500 static void LogToSinks(LogSeverity severity,
501 const char *full_filename,
502 const char *base_filename,
504 const struct ::tm* tm_time,
508 // Wait for all registered sinks via WaitTillSent
509 // including the optional one in "data".
510 static void WaitForSinks(LogMessage::LogMessageData* data);
512 static LogDestination* log_destination(LogSeverity severity);
514 LogFileObject fileobject_;
515 base::Logger* logger_; // Either &fileobject_, or wrapper around it
517 static LogDestination* log_destinations_[NUM_SEVERITIES];
518 static LogSeverity email_logging_severity_;
519 static string addresses_;
520 static string hostname_;
521 static bool terminal_supports_color_;
523 // arbitrary global logging destinations.
524 static vector<LogSink*>* sinks_;
526 // Protects the vector sinks_,
527 // but not the LogSink objects its elements reference.
528 static Mutex sink_mutex_;
531 LogDestination(const LogDestination&);
532 LogDestination& operator=(const LogDestination&);
535 // Errors do not get logged to email by default.
536 LogSeverity LogDestination::email_logging_severity_ = 99999;
538 string LogDestination::addresses_;
539 string LogDestination::hostname_;
541 vector<LogSink*>* LogDestination::sinks_ = NULL;
542 Mutex LogDestination::sink_mutex_;
543 bool LogDestination::terminal_supports_color_ = TerminalSupportsColor();
546 const string& LogDestination::hostname() {
547 if (hostname_.empty()) {
548 GetHostName(&hostname_);
549 if (hostname_.empty()) {
550 hostname_ = "(unknown)";
556 LogDestination::LogDestination(LogSeverity severity,
557 const char* base_filename)
558 : fileobject_(severity, base_filename),
559 logger_(&fileobject_) {
562 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
563 // assume we have the log_mutex or we simply don't care
565 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
566 LogDestination* log = log_destination(i);
568 // Flush the base fileobject_ logger directly instead of going
569 // through any wrappers to reduce chance of deadlock.
570 log->fileobject_.FlushUnlocked();
575 inline void LogDestination::FlushLogFiles(int min_severity) {
576 // Prevent any subtle race conditions by wrapping a mutex lock around
578 MutexLock l(&log_mutex);
579 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
580 LogDestination* log = log_destination(i);
582 log->logger_->Flush();
587 inline void LogDestination::SetLogDestination(LogSeverity severity,
588 const char* base_filename) {
589 assert(severity >= 0 && severity < NUM_SEVERITIES);
590 // Prevent any subtle race conditions by wrapping a mutex lock around
592 MutexLock l(&log_mutex);
593 log_destination(severity)->fileobject_.SetBasename(base_filename);
596 inline void LogDestination::SetLogSymlink(LogSeverity severity,
597 const char* symlink_basename) {
598 CHECK_GE(severity, 0);
599 CHECK_LT(severity, NUM_SEVERITIES);
600 MutexLock l(&log_mutex);
601 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
604 inline void LogDestination::AddLogSink(LogSink *destination) {
605 // Prevent any subtle race conditions by wrapping a mutex lock around
607 MutexLock l(&sink_mutex_);
608 if (!sinks_) sinks_ = new vector<LogSink*>;
609 sinks_->push_back(destination);
612 inline void LogDestination::RemoveLogSink(LogSink *destination) {
613 // Prevent any subtle race conditions by wrapping a mutex lock around
615 MutexLock l(&sink_mutex_);
616 // This doesn't keep the sinks in order, but who cares?
618 for (int i = sinks_->size() - 1; i >= 0; i--) {
619 if ((*sinks_)[i] == destination) {
620 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
628 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
629 // Prevent any subtle race conditions by wrapping a mutex lock around
631 MutexLock l(&log_mutex);
632 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
633 log_destination(severity)->fileobject_.SetExtension(ext);
637 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
638 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
639 // Prevent any subtle race conditions by wrapping a mutex lock around
641 MutexLock l(&log_mutex);
642 FLAGS_stderrthreshold = min_severity;
645 inline void LogDestination::LogToStderr() {
646 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
647 // SetLogDestination already do the locking!
648 SetStderrLogging(0); // thus everything is "also" logged to stderr
649 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
650 SetLogDestination(i, ""); // "" turns off logging to a logfile
654 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
655 const char* addresses) {
656 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
657 // Prevent any subtle race conditions by wrapping a mutex lock around
659 MutexLock l(&log_mutex);
660 LogDestination::email_logging_severity_ = min_severity;
661 LogDestination::addresses_ = addresses;
664 static void ColoredWriteToStderr(LogSeverity severity,
665 const char* message, size_t len) {
666 const GLogColor color =
667 (LogDestination::terminal_supports_color() && FLAGS_colorlogtostderr) ?
668 SeverityToColor(severity) : COLOR_DEFAULT;
670 // Avoid using cerr from this module since we may get called during
671 // exit code, and cerr may be partially or fully destroyed by then.
672 if (COLOR_DEFAULT == color) {
673 fwrite(message, len, 1, stderr);
677 const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
679 // Gets the current text color.
680 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
681 GetConsoleScreenBufferInfo(stderr_handle, &buffer_info);
682 const WORD old_color_attrs = buffer_info.wAttributes;
684 // We need to flush the stream buffers into the console before each
685 // SetConsoleTextAttribute call lest it affect the text that is already
686 // printed but has not yet reached the console.
688 SetConsoleTextAttribute(stderr_handle,
689 GetColorAttribute(color) | FOREGROUND_INTENSITY);
690 fwrite(message, len, 1, stderr);
692 // Restores the text color.
693 SetConsoleTextAttribute(stderr_handle, old_color_attrs);
695 fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color));
696 fwrite(message, len, 1, stderr);
697 fprintf(stderr, "\033[m"); // Resets the terminal to default.
701 static void WriteToStderr(const char* message, size_t len) {
702 // Avoid using cerr from this module since we may get called during
703 // exit code, and cerr may be partially or fully destroyed by then.
704 fwrite(message, len, 1, stderr);
707 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
708 const char* message, size_t len) {
709 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
710 ColoredWriteToStderr(severity, message, len);
712 // On Windows, also output to the debugger
713 ::OutputDebugStringA(string(message,len).c_str());
719 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
720 const char* message, size_t len) {
721 if (severity >= email_logging_severity_ ||
722 severity >= FLAGS_logemaillevel) {
723 string to(FLAGS_alsologtoemail);
724 if (!addresses_.empty()) {
730 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
731 glog_internal_namespace_::ProgramInvocationShortName());
732 string body(hostname());
734 body.append(message, len);
736 // should NOT use SendEmail(). The caller of this function holds the
737 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
738 // acquire the log_mutex object. Use SendEmailInternal() and set
739 // use_logging to false.
740 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
745 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
749 const bool should_flush = severity > FLAGS_logbuflevel;
750 LogDestination* destination = log_destination(severity);
751 destination->logger_->Write(should_flush, timestamp, message, len);
754 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
759 if ( FLAGS_logtostderr ) { // global flag: never log to file
760 ColoredWriteToStderr(severity, message, len);
762 for (int i = severity; i >= 0; --i)
763 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
767 inline void LogDestination::LogToSinks(LogSeverity severity,
768 const char *full_filename,
769 const char *base_filename,
771 const struct ::tm* tm_time,
773 size_t message_len) {
774 ReaderMutexLock l(&sink_mutex_);
776 for (int i = sinks_->size() - 1; i >= 0; i--) {
777 (*sinks_)[i]->send(severity, full_filename, base_filename,
778 line, tm_time, message, message_len);
783 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
784 ReaderMutexLock l(&sink_mutex_);
786 for (int i = sinks_->size() - 1; i >= 0; i--) {
787 (*sinks_)[i]->WaitTillSent();
790 const bool send_to_sink =
791 (data->send_method_ == &LogMessage::SendToSink) ||
792 (data->send_method_ == &LogMessage::SendToSinkAndLog);
793 if (send_to_sink && data->sink_ != NULL) {
794 data->sink_->WaitTillSent();
798 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
800 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
801 assert(severity >=0 && severity < NUM_SEVERITIES);
802 if (!log_destinations_[severity]) {
803 log_destinations_[severity] = new LogDestination(severity, NULL);
805 return log_destinations_[severity];
808 void LogDestination::DeleteLogDestinations() {
809 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
810 delete log_destinations_[severity];
811 log_destinations_[severity] = NULL;
817 LogFileObject::LogFileObject(LogSeverity severity,
818 const char* base_filename)
819 : base_filename_selected_(base_filename != NULL),
820 base_filename_((base_filename != NULL) ? base_filename : ""),
821 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
822 filename_extension_(),
825 bytes_since_flush_(0),
827 rollover_attempt_(kRolloverAttemptFrequency-1),
828 next_flush_time_(0) {
829 assert(severity >= 0);
830 assert(severity < NUM_SEVERITIES);
833 LogFileObject::~LogFileObject() {
841 void LogFileObject::SetBasename(const char* basename) {
843 base_filename_selected_ = true;
844 if (base_filename_ != basename) {
845 // Get rid of old log file since we are changing names
849 rollover_attempt_ = kRolloverAttemptFrequency-1;
851 base_filename_ = basename;
855 void LogFileObject::SetExtension(const char* ext) {
857 if (filename_extension_ != ext) {
858 // Get rid of old log file since we are changing names
862 rollover_attempt_ = kRolloverAttemptFrequency-1;
864 filename_extension_ = ext;
868 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
870 symlink_basename_ = symlink_basename;
873 void LogFileObject::Flush() {
878 void LogFileObject::FlushUnlocked(){
881 bytes_since_flush_ = 0;
883 // Figure out when we are due for another flush.
884 const int64 next = (FLAGS_logbufsecs
885 * static_cast<int64>(1000000)); // in usec
886 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
889 bool LogFileObject::CreateLogfile(const string& time_pid_string) {
890 string string_filename = base_filename_+filename_extension_+
892 const char* filename = string_filename.c_str();
893 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
894 if (fd == -1) return false;
896 // Mark the file close-on-exec. We don't really care if this fails
897 fcntl(fd, F_SETFD, FD_CLOEXEC);
900 file_ = fdopen(fd, "a"); // Make a FILE*.
901 if (file_ == NULL) { // Man, we're screwed!
903 unlink(filename); // Erase the half-baked evidence: an unusable log file
907 // We try to create a symlink called <program_name>.<severity>,
908 // which is easier to use. (Every time we create a new logfile,
909 // we destroy the old symlink and create a new one, so it always
910 // points to the latest logfile.) If it fails, we're sad but it's
912 if (!symlink_basename_.empty()) {
913 // take directory from filename
914 const char* slash = strrchr(filename, PATH_SEPARATOR);
915 const string linkname =
916 symlink_basename_ + '.' + LogSeverityNames[severity_];
918 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
919 linkpath += linkname;
920 unlink(linkpath.c_str()); // delete old one if it exists
922 #if defined(OS_WINDOWS)
923 // TODO(hamaji): Create lnk file on Windows?
924 #elif defined(HAVE_UNISTD_H)
925 // We must have unistd.h.
926 // Make the symlink be relative (in the same dir) so that if the
927 // entire log directory gets relocated the link is still valid.
928 const char *linkdest = slash ? (slash + 1) : filename;
929 if (symlink(linkdest, linkpath.c_str()) != 0) {
930 // silently ignore failures
933 // Make an additional link to the log file in a place specified by
934 // FLAGS_log_link, if indicated
935 if (!FLAGS_log_link.empty()) {
936 linkpath = FLAGS_log_link + "/" + linkname;
937 unlink(linkpath.c_str()); // delete old one if it exists
938 if (symlink(filename, linkpath.c_str()) != 0) {
939 // silently ignore failures
945 return true; // Everything worked
948 void LogFileObject::Write(bool force_flush,
954 // We don't log if the base_name_ is "" (which means "don't write")
955 if (base_filename_selected_ && base_filename_.empty()) {
959 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
961 if (file_ != NULL) fclose(file_);
963 file_length_ = bytes_since_flush_ = 0;
964 rollover_attempt_ = kRolloverAttemptFrequency-1;
967 // If there's no destination file, make one before outputting
969 // Try to rollover the log file every 32 log messages. The only time
970 // this could matter would be when we have trouble creating the log
971 // file. If that happens, we'll lose lots of log messages, of course!
972 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
973 rollover_attempt_ = 0;
976 localtime_r(×tamp, &tm_time);
978 // The logfile's filename will have the date/time & pid in it
979 ostringstream time_pid_stream;
980 time_pid_stream.fill('0');
981 time_pid_stream << 1900+tm_time.tm_year
982 << setw(2) << 1+tm_time.tm_mon
983 << setw(2) << tm_time.tm_mday
985 << setw(2) << tm_time.tm_hour
986 << setw(2) << tm_time.tm_min
987 << setw(2) << tm_time.tm_sec
989 << GetMainThreadPid();
990 const string& time_pid_string = time_pid_stream.str();
992 if (base_filename_selected_) {
993 if (!CreateLogfile(time_pid_string)) {
994 perror("Could not create log file");
995 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
996 time_pid_string.c_str());
1000 // If no base filename for logs of this severity has been set, use a
1001 // default base filename of
1002 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
1003 // logfiles will have names like
1004 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
1005 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
1006 // and 4354 is the pid of the logging process. The date & time reflect
1007 // when the file was created for output.
1009 // Where does the file get put? Successively try the directories
1011 string stripped_filename(
1012 glog_internal_namespace_::ProgramInvocationShortName());
1014 GetHostName(&hostname);
1016 string uidname = MyUserName();
1017 // We should not call CHECK() here because this function can be
1018 // called after holding on to log_mutex. We don't want to
1019 // attempt to hold on to the same mutex, and get into a
1020 // deadlock. Simply use a name like invalid-user.
1021 if (uidname.empty()) uidname = "invalid-user";
1023 stripped_filename = stripped_filename+'.'+hostname+'.'
1025 +LogSeverityNames[severity_]+'.';
1026 // We're going to (potentially) try to put logs in several different dirs
1027 const vector<string> & log_dirs = GetLoggingDirectories();
1029 // Go through the list of dirs, and try to create the log file in each
1030 // until we succeed or run out of options
1031 bool success = false;
1032 for (vector<string>::const_iterator dir = log_dirs.begin();
1033 dir != log_dirs.end();
1035 base_filename_ = *dir + "/" + stripped_filename;
1036 if ( CreateLogfile(time_pid_string) ) {
1041 // If we never succeeded, we have to give up
1042 if ( success == false ) {
1043 perror("Could not create logging file");
1044 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
1045 time_pid_string.c_str());
1050 // Write a header message into the log file
1051 ostringstream file_header_stream;
1052 file_header_stream.fill('0');
1053 file_header_stream << "Log file created at: "
1054 << 1900+tm_time.tm_year << '/'
1055 << setw(2) << 1+tm_time.tm_mon << '/'
1056 << setw(2) << tm_time.tm_mday
1058 << setw(2) << tm_time.tm_hour << ':'
1059 << setw(2) << tm_time.tm_min << ':'
1060 << setw(2) << tm_time.tm_sec << '\n'
1061 << "Running on machine: "
1062 << LogDestination::hostname() << '\n'
1063 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
1064 << "threadid file:line] msg" << '\n';
1065 const string& file_header_string = file_header_stream.str();
1067 const int header_len = file_header_string.size();
1068 fwrite(file_header_string.data(), 1, header_len, file_);
1069 file_length_ += header_len;
1070 bytes_since_flush_ += header_len;
1073 // Write to LOG file
1074 if ( !stop_writing ) {
1075 // fwrite() doesn't return an error when the disk is full, for
1076 // messages that are less than 4096 bytes. When the disk is full,
1077 // it returns the message length for messages that are less than
1078 // 4096 bytes. fwrite() returns 4096 for message lengths that are
1079 // greater than 4096, thereby indicating an error.
1081 fwrite(message, 1, message_len, file_);
1082 if ( FLAGS_stop_logging_if_full_disk &&
1083 errno == ENOSPC ) { // disk full, stop writing to disk
1084 stop_writing = true; // until the disk is
1087 file_length_ += message_len;
1088 bytes_since_flush_ += message_len;
1091 if ( CycleClock_Now() >= next_flush_time_ )
1092 stop_writing = false; // check to see if disk has free space.
1093 return; // no need to flush
1096 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
1097 // or every "FLAGS_logbufsecs" seconds.
1099 (bytes_since_flush_ >= 1000000) ||
1100 (CycleClock_Now() >= next_flush_time_) ) {
1103 if (FLAGS_drop_log_memory) {
1104 if (file_length_ >= logging::kPageSize) {
1105 // don't evict the most recent page
1106 uint32 len = file_length_ & ~(logging::kPageSize - 1);
1107 posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
1116 // An arbitrary limit on the length of a single log message. This
1117 // is so that streaming can be done more efficiently.
1118 const size_t LogMessage::kMaxLogMessageLen = 30000;
1120 // Static log data space to avoid alloc failures in a LOG(FATAL)
1122 // Since multiple threads may call LOG(FATAL), and we want to preserve
1123 // the data from the first call, we allocate two sets of space. One
1124 // for exclusive use by the first thread, and one for shared use by
1125 // all other threads.
1126 static Mutex fatal_msg_lock;
1127 static CrashReason crash_reason;
1128 static bool fatal_msg_exclusive = true;
1129 static char fatal_msg_buf_exclusive[LogMessage::kMaxLogMessageLen+1];
1130 static char fatal_msg_buf_shared[LogMessage::kMaxLogMessageLen+1];
1131 static LogMessage::LogStream fatal_msg_stream_exclusive(
1132 fatal_msg_buf_exclusive, LogMessage::kMaxLogMessageLen, 0);
1133 static LogMessage::LogStream fatal_msg_stream_shared(
1134 fatal_msg_buf_shared, LogMessage::kMaxLogMessageLen, 0);
1135 static LogMessage::LogMessageData fatal_msg_data_exclusive;
1136 static LogMessage::LogMessageData fatal_msg_data_shared;
1138 LogMessage::LogMessageData::~LogMessageData() {
1140 delete stream_alloc_;
1143 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1144 int ctr, void (LogMessage::*send_method)())
1145 : allocated_(NULL) {
1146 Init(file, line, severity, send_method);
1147 data_->stream_->set_ctr(ctr);
1150 LogMessage::LogMessage(const char* file, int line,
1151 const CheckOpString& result)
1152 : allocated_(NULL) {
1153 Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
1154 stream() << "Check failed: " << (*result.str_) << " ";
1157 LogMessage::LogMessage(const char* file, int line)
1158 : allocated_(NULL) {
1159 Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
1162 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
1163 : allocated_(NULL) {
1164 Init(file, line, severity, &LogMessage::SendToLog);
1167 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1168 LogSink* sink, bool also_send_to_log)
1169 : allocated_(NULL) {
1170 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
1171 &LogMessage::SendToSink);
1172 data_->sink_ = sink; // override Init()'s setting to NULL
1175 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1176 vector<string> *outvec)
1177 : allocated_(NULL) {
1178 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
1179 data_->outvec_ = outvec; // override Init()'s setting to NULL
1182 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1184 : allocated_(NULL) {
1185 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
1186 data_->message_ = message; // override Init()'s setting to NULL
1189 void LogMessage::Init(const char* file,
1191 LogSeverity severity,
1192 void (LogMessage::*send_method)()) {
1194 if (severity != GLOG_FATAL || !exit_on_dfatal) {
1195 allocated_ = new LogMessageData();
1197 data_->buf_ = new char[kMaxLogMessageLen+1];
1198 data_->message_text_ = data_->buf_;
1199 data_->stream_alloc_ =
1200 new LogStream(data_->message_text_, kMaxLogMessageLen, 0);
1201 data_->stream_ = data_->stream_alloc_;
1202 data_->first_fatal_ = false;
1204 MutexLock l(&fatal_msg_lock);
1205 if (fatal_msg_exclusive) {
1206 fatal_msg_exclusive = false;
1207 data_ = &fatal_msg_data_exclusive;
1208 data_->message_text_ = fatal_msg_buf_exclusive;
1209 data_->stream_ = &fatal_msg_stream_exclusive;
1210 data_->first_fatal_ = true;
1212 data_ = &fatal_msg_data_shared;
1213 data_->message_text_ = fatal_msg_buf_shared;
1214 data_->stream_ = &fatal_msg_stream_shared;
1215 data_->first_fatal_ = false;
1217 data_->stream_alloc_ = NULL;
1221 data_->preserved_errno_ = errno;
1222 data_->severity_ = severity;
1223 data_->line_ = line;
1224 data_->send_method_ = send_method;
1225 data_->sink_ = NULL;
1226 data_->outvec_ = NULL;
1227 WallTime now = WallTime_Now();
1228 data_->timestamp_ = static_cast<time_t>(now);
1229 localtime_r(&data_->timestamp_, &data_->tm_time_);
1230 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1231 RawLog__SetLastTime(data_->tm_time_, usecs);
1233 data_->num_chars_to_log_ = 0;
1234 data_->num_chars_to_syslog_ = 0;
1235 data_->basename_ = const_basename(file);
1236 data_->fullname_ = file;
1237 data_->has_been_flushed_ = false;
1239 // If specified, prepend a prefix to each line. For example:
1240 // I1018 160715 f5d4fbb0 logging.cc:1153]
1241 // (log level, GMT month, date, time, thread_id, file basename, line)
1242 // We exclude the thread_id for the default thread.
1243 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1244 stream() << LogSeverityNames[severity][0]
1245 << setw(2) << 1+data_->tm_time_.tm_mon
1246 << setw(2) << data_->tm_time_.tm_mday
1248 << setw(2) << data_->tm_time_.tm_hour << ':'
1249 << setw(2) << data_->tm_time_.tm_min << ':'
1250 << setw(2) << data_->tm_time_.tm_sec << "."
1253 << setfill(' ') << setw(5)
1254 << static_cast<unsigned int>(GetTID()) << setfill('0')
1256 << data_->basename_ << ':' << data_->line_ << "] ";
1258 data_->num_prefix_chars_ = data_->stream_->pcount();
1260 if (!FLAGS_log_backtrace_at.empty()) {
1262 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1263 #ifdef HAVE_STACKTRACE
1264 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1266 DumpStackTraceToString(&stacktrace);
1267 stream() << " (stacktrace:\n" << stacktrace << ") ";
1273 LogMessage::~LogMessage() {
1278 int LogMessage::preserved_errno() const {
1279 return data_->preserved_errno_;
1282 ostream& LogMessage::stream() {
1283 return *(data_->stream_);
1286 // Flush buffered message, called by the destructor, or any other function
1287 // that needs to synchronize the log.
1288 void LogMessage::Flush() {
1289 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1292 data_->num_chars_to_log_ = data_->stream_->pcount();
1293 data_->num_chars_to_syslog_ =
1294 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1296 // Do we need to add a \n to the end of this message?
1297 bool append_newline =
1298 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1299 char original_final_char = '\0';
1301 // If we do need to add a \n, we'll do it by violating the memory of the
1302 // ostrstream buffer. This is quick, and we'll make sure to undo our
1303 // modification before anything else is done with the ostrstream. It
1304 // would be preferable not to do things this way, but it seems to be
1305 // the best way to deal with this.
1306 if (append_newline) {
1307 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1308 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1311 // Prevent any subtle race conditions by wrapping a mutex lock around
1312 // the actual logging action per se.
1314 MutexLock l(&log_mutex);
1315 (this->*(data_->send_method_))();
1316 ++num_messages_[static_cast<int>(data_->severity_)];
1318 LogDestination::WaitForSinks(data_);
1320 if (append_newline) {
1321 // Fix the ostrstream back how it was before we screwed with it.
1322 // It's 99.44% certain that we don't need to worry about doing this.
1323 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1326 // If errno was already set before we enter the logging call, we'll
1327 // set it back to that value when we return from the logging call.
1328 // It happens often that we log an error message after a syscall
1329 // failure, which can potentially set the errno to some other
1330 // values. We would like to preserve the original errno.
1331 if (data_->preserved_errno_ != 0) {
1332 errno = data_->preserved_errno_;
1335 // Note that this message is now safely logged. If we're asked to flush
1336 // again, as a result of destruction, say, we'll do nothing on future calls.
1337 data_->has_been_flushed_ = true;
1340 // Copy of first FATAL log message so that we can print it out again
1341 // after all the stack traces. To preserve legacy behavior, we don't
1342 // use fatal_msg_buf_exclusive.
1343 static time_t fatal_time;
1344 static char fatal_message[256];
1346 void ReprintFatalMessage() {
1347 if (fatal_message[0]) {
1348 const int n = strlen(fatal_message);
1349 if (!FLAGS_logtostderr) {
1350 // Also write to stderr (don't color to avoid terminal checks)
1351 WriteToStderr(fatal_message, n);
1353 LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1357 // L >= log_mutex (callers must hold the log_mutex).
1358 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1359 static bool already_warned_before_initgoogle = false;
1361 log_mutex.AssertHeld();
1363 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1364 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1366 // Messages of a given severity get logged to lower severity logs, too
1368 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1369 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1370 "written to STDERR\n";
1371 WriteToStderr(w, strlen(w));
1372 already_warned_before_initgoogle = true;
1375 // global flag: never log to file if set. Also -- don't log to a
1376 // file if we haven't parsed the command line flags to get the
1378 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1379 ColoredWriteToStderr(data_->severity_,
1380 data_->message_text_, data_->num_chars_to_log_);
1382 // this could be protected by a flag if necessary.
1383 LogDestination::LogToSinks(data_->severity_,
1384 data_->fullname_, data_->basename_,
1385 data_->line_, &data_->tm_time_,
1386 data_->message_text_ + data_->num_prefix_chars_,
1387 (data_->num_chars_to_log_ -
1388 data_->num_prefix_chars_ - 1));
1391 // log this message to all log files of severity <= severity_
1392 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1393 data_->message_text_,
1394 data_->num_chars_to_log_);
1396 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1397 data_->num_chars_to_log_);
1398 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1399 data_->num_chars_to_log_);
1400 LogDestination::LogToSinks(data_->severity_,
1401 data_->fullname_, data_->basename_,
1402 data_->line_, &data_->tm_time_,
1403 data_->message_text_ + data_->num_prefix_chars_,
1404 (data_->num_chars_to_log_
1405 - data_->num_prefix_chars_ - 1));
1406 // NOTE: -1 removes trailing \n
1409 // If we log a FATAL message, flush all the log destinations, then toss
1410 // a signal for others to catch. We leave the logs in a state that
1411 // someone else can use them (as long as they flush afterwards)
1412 if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1413 if (data_->first_fatal_) {
1414 // Store crash information so that it is accessible from within signal
1415 // handlers that may be invoked later.
1416 RecordCrashReason(&crash_reason);
1417 SetCrashReason(&crash_reason);
1419 // Store shortened fatal message for other logs and GWQ status
1420 const int copy = min<int>(data_->num_chars_to_log_,
1421 sizeof(fatal_message)-1);
1422 memcpy(fatal_message, data_->message_text_, copy);
1423 fatal_message[copy] = '\0';
1424 fatal_time = data_->timestamp_;
1427 if (!FLAGS_logtostderr) {
1428 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1429 if ( LogDestination::log_destinations_[i] )
1430 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1434 // release the lock that our caller (directly or indirectly)
1435 // LogMessage::~LogMessage() grabbed so that signal handlers
1436 // can use the logging facility. Alternately, we could add
1437 // an entire unsafe logging interface to bypass locking
1438 // for signal handlers but this seems simpler.
1440 LogDestination::WaitForSinks(data_);
1442 const char* message = "*** Check failure stack trace: ***\n";
1443 if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1450 void LogMessage::RecordCrashReason(
1451 glog_internal_namespace_::CrashReason* reason) {
1452 reason->filename = fatal_msg_data_exclusive.fullname_;
1453 reason->line_number = fatal_msg_data_exclusive.line_;
1454 reason->message = fatal_msg_buf_exclusive +
1455 fatal_msg_data_exclusive.num_prefix_chars_;
1456 #ifdef HAVE_STACKTRACE
1457 // Retrieve the stack trace, omitting the logging frames that got us here.
1458 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1464 #ifdef HAVE___ATTRIBUTE__
1465 # define ATTRIBUTE_NORETURN __attribute__((noreturn))
1467 # define ATTRIBUTE_NORETURN
1470 static void logging_fail() ATTRIBUTE_NORETURN;
1472 static void logging_fail() {
1473 #if defined(_DEBUG) && defined(_MSC_VER)
1474 // When debugging on windows, avoid the obnoxious dialog and make
1475 // it possible to continue past a LOG(FATAL) in the debugger
1482 typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN;
1484 GOOGLE_GLOG_DLL_DECL
1485 logging_fail_func_t g_logging_fail_func = &logging_fail;
1487 void InstallFailureFunction(void (*fail_func)()) {
1488 g_logging_fail_func = (logging_fail_func_t)fail_func;
1491 void LogMessage::Fail() {
1492 g_logging_fail_func();
1495 // L >= log_mutex (callers must hold the log_mutex).
1496 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1497 if (data_->sink_ != NULL) {
1498 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1499 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1500 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1501 data_->line_, &data_->tm_time_,
1502 data_->message_text_ + data_->num_prefix_chars_,
1503 (data_->num_chars_to_log_ -
1504 data_->num_prefix_chars_ - 1));
1508 // L >= log_mutex (callers must hold the log_mutex).
1509 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1514 // L >= log_mutex (callers must hold the log_mutex).
1515 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1516 if (data_->outvec_ != NULL) {
1517 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1518 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1519 // Omit prefix of message and trailing newline when recording in outvec_.
1520 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1521 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1522 data_->outvec_->push_back(string(start, len));
1528 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1529 if (data_->message_ != NULL) {
1530 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1531 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1532 // Omit prefix of message and trailing newline when writing to message_.
1533 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1534 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1535 data_->message_->assign(start, len);
1540 // L >= log_mutex (callers must hold the log_mutex).
1541 void LogMessage::SendToSyslogAndLog() {
1542 #ifdef HAVE_SYSLOG_H
1543 // Before any calls to syslog(), make a single call to openlog()
1544 static bool openlog_already_called = false;
1545 if (!openlog_already_called) {
1546 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1547 LOG_CONS | LOG_NDELAY | LOG_PID,
1549 openlog_already_called = true;
1552 // This array maps Google severity levels to syslog levels
1553 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1554 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1555 int(data_->num_chars_to_syslog_),
1556 data_->message_text_ + data_->num_prefix_chars_);
1559 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1563 base::Logger* base::GetLogger(LogSeverity severity) {
1564 MutexLock l(&log_mutex);
1565 return LogDestination::log_destination(severity)->logger_;
1568 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1569 MutexLock l(&log_mutex);
1570 LogDestination::log_destination(severity)->logger_ = logger;
1573 // L < log_mutex. Acquires and releases mutex_.
1574 int64 LogMessage::num_messages(int severity) {
1575 MutexLock l(&log_mutex);
1576 return num_messages_[severity];
1579 // Output the COUNTER value. This is only valid if ostream is a
1581 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1583 LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
1585 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1587 CHECK(log && log == log->self())
1588 << "You must not use COUNTER with non-glog ostream";
1593 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1594 LogSeverity severity, int ctr,
1595 void (LogMessage::*send_method)())
1596 : LogMessage(file, line, severity, ctr, send_method) {
1599 ErrnoLogMessage::~ErrnoLogMessage() {
1600 // Don't access errno directly because it may have been altered
1601 // while streaming the message.
1603 posix_strerror_r(preserved_errno(), buf, sizeof(buf));
1604 stream() << ": " << buf << " [" << preserved_errno() << "]";
1607 void FlushLogFiles(LogSeverity min_severity) {
1608 LogDestination::FlushLogFiles(min_severity);
1611 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1612 LogDestination::FlushLogFilesUnsafe(min_severity);
1615 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1616 LogDestination::SetLogDestination(severity, base_filename);
1619 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1620 LogDestination::SetLogSymlink(severity, symlink_basename);
1623 LogSink::~LogSink() {
1626 void LogSink::WaitTillSent() {
1630 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1631 const struct ::tm* tm_time,
1632 const char* message, size_t message_len) {
1633 ostringstream stream(string(message, message_len));
1636 // FIXME(jrvb): Updating this to use the correct value for usecs
1637 // requires changing the signature for both this method and
1638 // LogSink::send(). This change needs to be done in a separate CL
1639 // so subclasses of LogSink can be updated at the same time.
1642 stream << LogSeverityNames[severity][0]
1643 << setw(2) << 1+tm_time->tm_mon
1644 << setw(2) << tm_time->tm_mday
1646 << setw(2) << tm_time->tm_hour << ':'
1647 << setw(2) << tm_time->tm_min << ':'
1648 << setw(2) << tm_time->tm_sec << '.'
1651 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1653 << file << ':' << line << "] ";
1655 stream << string(message, message_len);
1656 return stream.str();
1659 void AddLogSink(LogSink *destination) {
1660 LogDestination::AddLogSink(destination);
1663 void RemoveLogSink(LogSink *destination) {
1664 LogDestination::RemoveLogSink(destination);
1667 void SetLogFilenameExtension(const char* ext) {
1668 LogDestination::SetLogFilenameExtension(ext);
1671 void SetStderrLogging(LogSeverity min_severity) {
1672 LogDestination::SetStderrLogging(min_severity);
1675 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1676 LogDestination::SetEmailLogging(min_severity, addresses);
1679 void LogToStderr() {
1680 LogDestination::LogToStderr();
1684 namespace internal {
1686 bool GetExitOnDFatal() {
1687 MutexLock l(&log_mutex);
1688 return exit_on_dfatal;
1691 // Determines whether we exit the program for a LOG(DFATAL) message in
1692 // debug mode. It does this by skipping the call to Fail/FailQuietly.
1693 // This is intended for testing only.
1695 // This can have some effects on LOG(FATAL) as well. Failure messages
1696 // are always allocated (rather than sharing a buffer), the crash
1697 // reason is not recorded, the "gwq" status message is not updated,
1698 // and the stack trace is not recorded. The LOG(FATAL) *will* still
1699 // exit the program. Since this function is used only in testing,
1700 // these differences are acceptable.
1701 void SetExitOnDFatal(bool value) {
1702 MutexLock l(&log_mutex);
1703 exit_on_dfatal = value;
1706 } // namespace internal
1709 // use_logging controls whether the logging functions LOG/VLOG are used
1710 // to log errors. It should be set to false when the caller holds the
1712 static bool SendEmailInternal(const char*dest, const char *subject,
1713 const char*body, bool use_logging) {
1714 if (dest && *dest) {
1715 if ( use_logging ) {
1716 VLOG(1) << "Trying to send TITLE:" << subject
1717 << " BODY:" << body << " to " << dest;
1719 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1720 subject, body, dest);
1724 FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1725 FILE* pipe = popen(cmd.c_str(), "w");
1727 // Add the body if we have one
1729 fwrite(body, sizeof(char), strlen(body), pipe);
1730 bool ok = pclose(pipe) != -1;
1732 if ( use_logging ) {
1734 posix_strerror_r(errno, buf, sizeof(buf));
1735 LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf;
1738 posix_strerror_r(errno, buf, sizeof(buf));
1739 fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf);
1744 if ( use_logging ) {
1745 LOG(ERROR) << "Unable to send mail to " << dest;
1747 fprintf(stderr, "Unable to send mail to %s\n", dest);
1754 bool SendEmail(const char*dest, const char *subject, const char*body){
1755 return SendEmailInternal(dest, subject, body, true);
1758 static void GetTempDirectories(vector<string>* list) {
1761 // On windows we'll try to find a directory in this order:
1762 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1765 // C:/WINDOWS/ or C:/WINNT/
1768 if (GetTempPathA(MAX_PATH, tmp))
1769 list->push_back(tmp);
1770 list->push_back("C:\\tmp\\");
1771 list->push_back("C:\\temp\\");
1773 // Directories, in order of preference. If we find a dir that
1774 // exists, we stop adding other less-preferred dirs
1775 const char * candidates[] = {
1776 // Non-null only during unittest/regtest
1777 getenv("TEST_TMPDIR"),
1779 // Explicitly-supplied temp dirs
1780 getenv("TMPDIR"), getenv("TMP"),
1782 // If all else fails
1786 for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
1787 const char *d = candidates[i];
1788 if (!d) continue; // Empty env var
1790 // Make sure we don't surprise anyone who's expecting a '/'
1792 if (dstr[dstr.size() - 1] != '/') {
1795 list->push_back(dstr);
1797 struct stat statbuf;
1798 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1799 // We found a dir that exists - we're done.
1807 static vector<string>* logging_directories_list;
1809 const vector<string>& GetLoggingDirectories() {
1810 // Not strictly thread-safe but we're called early in InitGoogle().
1811 if (logging_directories_list == NULL) {
1812 logging_directories_list = new vector<string>;
1814 if ( !FLAGS_log_dir.empty() ) {
1815 // A dir was specified, we should use it
1816 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1818 GetTempDirectories(logging_directories_list);
1821 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1822 logging_directories_list->push_back(tmp);
1823 logging_directories_list->push_back(".\\");
1825 logging_directories_list->push_back("./");
1829 return *logging_directories_list;
1832 void TestOnly_ClearLoggingDirectoriesList() {
1833 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1834 "called from test code.\n");
1835 delete logging_directories_list;
1836 logging_directories_list = NULL;
1839 void GetExistingTempDirectories(vector<string>* list) {
1840 GetTempDirectories(list);
1841 vector<string>::iterator i_dir = list->begin();
1842 while( i_dir != list->end() ) {
1843 // zero arg to access means test for existence; no constant
1844 // defined on windows
1845 if ( access(i_dir->c_str(), 0) ) {
1846 i_dir = list->erase(i_dir);
1853 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1854 #ifdef HAVE_UNISTD_H
1855 struct stat statbuf;
1856 const int kCopyBlockSize = 8 << 10;
1857 char copybuf[kCopyBlockSize];
1858 int64 read_offset, write_offset;
1859 // Don't follow symlinks unless they're our own fd symlinks in /proc
1861 // TODO(hamaji): Support other environments.
1863 const char *procfd_prefix = "/proc/self/fd/";
1864 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1867 int fd = open(path, flags);
1869 if (errno == EFBIG) {
1870 // The log file in question has got too big for us to open. The
1871 // real fix for this would be to compile logging.cc (or probably
1872 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1874 // Instead just truncate the file to something we can manage
1875 if (truncate(path, 0) == -1) {
1876 PLOG(ERROR) << "Unable to truncate " << path;
1878 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1881 PLOG(ERROR) << "Unable to open " << path;
1886 if (fstat(fd, &statbuf) == -1) {
1887 PLOG(ERROR) << "Unable to fstat()";
1891 // See if the path refers to a regular file bigger than the
1893 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1894 if (statbuf.st_size <= limit) goto out_close_fd;
1895 if (statbuf.st_size <= keep) goto out_close_fd;
1897 // This log file is too large - we need to truncate it
1898 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1900 // Copy the last "keep" bytes of the file to the beginning of the file
1901 read_offset = statbuf.st_size - keep;
1903 int bytesin, bytesout;
1904 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1905 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1906 if (bytesout == -1) {
1907 PLOG(ERROR) << "Unable to write to " << path;
1909 } else if (bytesout != bytesin) {
1910 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1912 read_offset += bytesin;
1913 write_offset += bytesout;
1915 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1917 // Truncate the remainder of the file. If someone else writes to the
1918 // end of the file after our last read() above, we lose their latest
1919 // data. Too bad ...
1920 if (ftruncate(fd, write_offset) == -1) {
1921 PLOG(ERROR) << "Unable to truncate " << path;
1927 LOG(ERROR) << "No log truncation support.";
1931 void TruncateStdoutStderr() {
1932 #ifdef HAVE_UNISTD_H
1933 int64 limit = MaxLogSize() << 20;
1934 int64 keep = 1 << 20;
1935 TruncateLogFile("/proc/self/fd/1", limit, keep);
1936 TruncateLogFile("/proc/self/fd/2", limit, keep);
1938 LOG(ERROR) << "No log truncation support.";
1943 // Helper functions for string comparisons.
1944 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1945 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1946 const char* names) { \
1947 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1948 if (equal == expected) return NULL; \
1953 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1954 return new string(ss.str()); \
1957 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1958 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1959 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1960 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1961 #undef DEFINE_CHECK_STROP_IMPL
1963 int posix_strerror_r(int err, char *buf, size_t len) {
1964 // Sanity check input parameters
1965 if (buf == NULL || len <= 0) {
1970 // Reset buf and errno, and try calling whatever version of strerror_r()
1971 // is implemented by glibc
1973 int old_errno = errno;
1975 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1977 // Both versions set errno on failure
1979 // Should already be there, but better safe than sorry
1985 // POSIX is vague about whether the string will be terminated, although
1986 // is indirectly implies that typically ERANGE will be returned, instead
1987 // of truncating the string. This is different from the GNU implementation.
1988 // We play it safe by always terminating the string explicitly.
1989 buf[len-1] = '\000';
1991 // If the function succeeded, we can use its exit code to determine the
1992 // semantics implemented by glibc
1996 // GNU semantics detected
2001 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
2002 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
2003 // This means an error on MacOSX or FreeBSD.
2007 strncat(buf, rc, len-1);
2013 LogMessageFatal::LogMessageFatal(const char* file, int line) :
2014 LogMessage(file, line, GLOG_FATAL) {}
2016 LogMessageFatal::LogMessageFatal(const char* file, int line,
2017 const CheckOpString& result) :
2018 LogMessage(file, line, result) {}
2020 LogMessageFatal::~LogMessageFatal() {
2027 CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
2028 : stream_(new ostringstream) {
2029 *stream_ << exprtext << " (";
2032 CheckOpMessageBuilder::~CheckOpMessageBuilder() {
2036 ostream* CheckOpMessageBuilder::ForVar2() {
2037 *stream_ << " vs. ";
2041 string* CheckOpMessageBuilder::NewString() {
2043 return new string(stream_->str());
2049 void MakeCheckOpValueString(std::ostream* os, const char& v) {
2050 if (v >= 32 && v <= 126) {
2051 (*os) << "'" << v << "'";
2053 (*os) << "char value " << (short)v;
2058 void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
2059 if (v >= 32 && v <= 126) {
2060 (*os) << "'" << v << "'";
2062 (*os) << "signed char value " << (short)v;
2067 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
2068 if (v >= 32 && v <= 126) {
2069 (*os) << "'" << v << "'";
2071 (*os) << "unsigned char value " << (unsigned short)v;
2075 void InitGoogleLogging(const char* argv0) {
2076 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
2079 void ShutdownGoogleLogging() {
2080 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
2081 LogDestination::DeleteLogDestinations();
2082 delete logging_directories_list;
2083 logging_directories_list = NULL;
2086 _END_GOOGLE_NAMESPACE_