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 '/'
182 static void GetHostName(string* hostname) {
183 #if defined(HAVE_SYS_UTSNAME_H)
185 if (0 != uname(&buf)) {
186 // ensure null termination on failure
187 *buf.nodename = '\0';
189 *hostname = buf.nodename;
190 #elif defined(OS_WINDOWS)
191 char buf[MAX_COMPUTERNAME_LENGTH + 1];
192 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
193 if (GetComputerNameA(buf, &len)) {
199 # warning There is no way to retrieve the host name.
200 *hostname = "(unknown)";
204 // Returns true iff terminal supports using colors in output.
205 static bool TerminalSupportsColor() {
206 bool term_supports_color = false;
208 // on Windows TERM variable is usually not set, but the console does
210 term_supports_color = true;
212 // On non-Windows platforms, we rely on the TERM variable.
213 const char* const term = getenv("TERM");
214 if (term != NULL && term[0] != '\0') {
215 term_supports_color =
216 !strcmp(term, "xterm") ||
217 !strcmp(term, "xterm-color") ||
218 !strcmp(term, "xterm-256color") ||
219 !strcmp(term, "screen") ||
220 !strcmp(term, "linux") ||
221 !strcmp(term, "cygwin");
224 return term_supports_color;
227 _START_GOOGLE_NAMESPACE_
236 static GLogColor SeverityToColor(LogSeverity severity) {
237 assert(severity >= 0 && severity < NUM_SEVERITIES);
238 GLogColor color = COLOR_DEFAULT;
241 color = COLOR_DEFAULT;
244 color = COLOR_YELLOW;
251 // should never get here.
259 // Returns the character attribute for the given color.
260 WORD GetColorAttribute(GLogColor color) {
262 case COLOR_RED: return FOREGROUND_RED;
263 case COLOR_GREEN: return FOREGROUND_GREEN;
264 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
271 // Returns the ANSI color code for the given color.
272 const char* GetAnsiColorCode(GLogColor color) {
274 case COLOR_RED: return "1";
275 case COLOR_GREEN: return "2";
276 case COLOR_YELLOW: return "3";
277 case COLOR_DEFAULT: return "";
279 return NULL; // stop warning about return type.
284 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
285 static int32 MaxLogSize() {
286 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
289 struct LogMessage::LogMessageData {
292 int preserved_errno_; // preserved errno
293 char* buf_; // buffer space for non FATAL messages
294 char* message_text_; // Complete message text (points to selected buffer)
295 LogStream* stream_alloc_;
297 char severity_; // What level is this LogMessage logged at?
298 int line_; // line number where logging call is.
299 void (LogMessage::*send_method_)(); // Call this in destructor to send
300 union { // At most one of these is used: union to keep the size low.
301 LogSink* sink_; // NULL or sink to send message to
302 std::vector<std::string>* outvec_; // NULL or vector to push message onto
303 std::string* message_; // NULL or string to write message into
305 time_t timestamp_; // Time of creation of LogMessage
306 struct ::tm tm_time_; // Time of creation of LogMessage
307 size_t num_prefix_chars_; // # of chars of prefix in this message
308 size_t num_chars_to_log_; // # of chars of msg to send to log
309 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
310 const char* basename_; // basename of file that called LOG
311 const char* fullname_; // fullname of file that called LOG
312 bool has_been_flushed_; // false => data has not been flushed
313 bool first_fatal_; // true => this was first fatal msg
318 LogMessageData(const LogMessageData&);
319 void operator=(const LogMessageData&);
322 // A mutex that allows only one thread to log at a time, to keep things from
323 // getting jumbled. Some other very uncommon logging operations (like
324 // changing the destination file for log messages of a given severity) also
325 // lock this mutex. Please be sure that anybody who might possibly need to
327 static Mutex log_mutex;
329 // Number of messages sent at each severity. Under log_mutex.
330 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
332 // Globally disable log writing (if disk is full)
333 static bool stop_writing = false;
335 const char*const LogSeverityNames[NUM_SEVERITIES] = {
336 "INFO", "WARNING", "ERROR", "FATAL"
339 // Has the user called SetExitOnDFatal(true)?
340 static bool exit_on_dfatal = true;
342 const char* GetLogSeverityName(LogSeverity severity) {
343 return LogSeverityNames[severity];
346 static bool SendEmailInternal(const char*dest, const char *subject,
347 const char*body, bool use_logging);
349 base::Logger::~Logger() {
354 // Encapsulates all file-system related state
355 class LogFileObject : public base::Logger {
357 LogFileObject(LogSeverity severity, const char* base_filename);
360 virtual void Write(bool force_flush, // Should we force a flush here?
361 time_t timestamp, // Timestamp for this entry
365 // Configuration options
366 void SetBasename(const char* basename);
367 void SetExtension(const char* ext);
368 void SetSymlinkBasename(const char* symlink_basename);
370 // Normal flushing routine
371 virtual void Flush();
373 // It is the actual file length for the system loggers,
374 // i.e., INFO, ERROR, etc.
375 virtual uint32 LogSize() {
380 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
381 // can avoid grabbing a lock. Usually Flush() calls it after
383 void FlushUnlocked();
386 static const uint32 kRolloverAttemptFrequency = 0x20;
389 bool base_filename_selected_;
390 string base_filename_;
391 string symlink_basename_;
392 string filename_extension_; // option users can specify (eg to add port#)
394 LogSeverity severity_;
395 uint32 bytes_since_flush_;
397 unsigned int rollover_attempt_;
398 int64 next_flush_time_; // cycle count at which to flush log
400 // Actually create a logfile using the value of base_filename_ and the
401 // supplied argument time_pid_string
402 // REQUIRES: lock_ is held
403 bool CreateLogfile(const string& time_pid_string);
408 class LogDestination {
410 friend class LogMessage;
411 friend void ReprintFatalMessage();
412 friend base::Logger* base::GetLogger(LogSeverity);
413 friend void base::SetLogger(LogSeverity, base::Logger*);
415 // These methods are just forwarded to by their global versions.
416 static void SetLogDestination(LogSeverity severity,
417 const char* base_filename);
418 static void SetLogSymlink(LogSeverity severity,
419 const char* symlink_basename);
420 static void AddLogSink(LogSink *destination);
421 static void RemoveLogSink(LogSink *destination);
422 static void SetLogFilenameExtension(const char* filename_extension);
423 static void SetStderrLogging(LogSeverity min_severity);
424 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
425 static void LogToStderr();
426 // Flush all log files that are at least at the given severity level
427 static void FlushLogFiles(int min_severity);
428 static void FlushLogFilesUnsafe(int min_severity);
430 // we set the maximum size of our packet to be 1400, the logic being
431 // to prevent fragmentation.
432 // Really this number is arbitrary.
433 static const int kNetworkBytes = 1400;
435 static const string& hostname();
436 static const bool& terminal_supports_color() {
437 return terminal_supports_color_;
440 static void DeleteLogDestinations();
443 LogDestination(LogSeverity severity, const char* base_filename);
444 ~LogDestination() { }
446 // Take a log message of a particular severity and log it to stderr
447 // iff it's of a high enough severity to deserve it.
448 static void MaybeLogToStderr(LogSeverity severity, const char* message,
451 // Take a log message of a particular severity and log it to email
452 // iff it's of a high enough severity to deserve it.
453 static void MaybeLogToEmail(LogSeverity severity, const char* message,
455 // Take a log message of a particular severity and log it to a file
456 // iff the base filename is not "" (which means "don't log to me")
457 static void MaybeLogToLogfile(LogSeverity severity,
459 const char* message, size_t len);
460 // Take a log message of a particular severity and log it to the file
461 // for that severity and also for all files with severity less than
463 static void LogToAllLogfiles(LogSeverity severity,
465 const char* message, size_t len);
467 // Send logging info to all registered sinks.
468 static void LogToSinks(LogSeverity severity,
469 const char *full_filename,
470 const char *base_filename,
472 const struct ::tm* tm_time,
476 // Wait for all registered sinks via WaitTillSent
477 // including the optional one in "data".
478 static void WaitForSinks(LogMessage::LogMessageData* data);
480 static LogDestination* log_destination(LogSeverity severity);
482 LogFileObject fileobject_;
483 base::Logger* logger_; // Either &fileobject_, or wrapper around it
485 static LogDestination* log_destinations_[NUM_SEVERITIES];
486 static LogSeverity email_logging_severity_;
487 static string addresses_;
488 static string hostname_;
489 static bool terminal_supports_color_;
491 // arbitrary global logging destinations.
492 static vector<LogSink*>* sinks_;
494 // Protects the vector sinks_,
495 // but not the LogSink objects its elements reference.
496 static Mutex sink_mutex_;
499 LogDestination(const LogDestination&);
500 LogDestination& operator=(const LogDestination&);
503 // Errors do not get logged to email by default.
504 LogSeverity LogDestination::email_logging_severity_ = 99999;
506 string LogDestination::addresses_;
507 string LogDestination::hostname_;
509 vector<LogSink*>* LogDestination::sinks_ = NULL;
510 Mutex LogDestination::sink_mutex_;
511 bool LogDestination::terminal_supports_color_ = TerminalSupportsColor();
514 const string& LogDestination::hostname() {
515 if (hostname_.empty()) {
516 GetHostName(&hostname_);
517 if (hostname_.empty()) {
518 hostname_ = "(unknown)";
524 LogDestination::LogDestination(LogSeverity severity,
525 const char* base_filename)
526 : fileobject_(severity, base_filename),
527 logger_(&fileobject_) {
530 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
531 // assume we have the log_mutex or we simply don't care
533 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
534 LogDestination* log = log_destination(i);
536 // Flush the base fileobject_ logger directly instead of going
537 // through any wrappers to reduce chance of deadlock.
538 log->fileobject_.FlushUnlocked();
543 inline void LogDestination::FlushLogFiles(int min_severity) {
544 // Prevent any subtle race conditions by wrapping a mutex lock around
546 MutexLock l(&log_mutex);
547 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
548 LogDestination* log = log_destination(i);
550 log->logger_->Flush();
555 inline void LogDestination::SetLogDestination(LogSeverity severity,
556 const char* base_filename) {
557 assert(severity >= 0 && severity < NUM_SEVERITIES);
558 // Prevent any subtle race conditions by wrapping a mutex lock around
560 MutexLock l(&log_mutex);
561 log_destination(severity)->fileobject_.SetBasename(base_filename);
564 inline void LogDestination::SetLogSymlink(LogSeverity severity,
565 const char* symlink_basename) {
566 CHECK_GE(severity, 0);
567 CHECK_LT(severity, NUM_SEVERITIES);
568 MutexLock l(&log_mutex);
569 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
572 inline void LogDestination::AddLogSink(LogSink *destination) {
573 // Prevent any subtle race conditions by wrapping a mutex lock around
575 MutexLock l(&sink_mutex_);
576 if (!sinks_) sinks_ = new vector<LogSink*>;
577 sinks_->push_back(destination);
580 inline void LogDestination::RemoveLogSink(LogSink *destination) {
581 // Prevent any subtle race conditions by wrapping a mutex lock around
583 MutexLock l(&sink_mutex_);
584 // This doesn't keep the sinks in order, but who cares?
586 for (int i = sinks_->size() - 1; i >= 0; i--) {
587 if ((*sinks_)[i] == destination) {
588 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
596 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
597 // Prevent any subtle race conditions by wrapping a mutex lock around
599 MutexLock l(&log_mutex);
600 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
601 log_destination(severity)->fileobject_.SetExtension(ext);
605 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
606 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
607 // Prevent any subtle race conditions by wrapping a mutex lock around
609 MutexLock l(&log_mutex);
610 FLAGS_stderrthreshold = min_severity;
613 inline void LogDestination::LogToStderr() {
614 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
615 // SetLogDestination already do the locking!
616 SetStderrLogging(0); // thus everything is "also" logged to stderr
617 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
618 SetLogDestination(i, ""); // "" turns off logging to a logfile
622 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
623 const char* addresses) {
624 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
625 // Prevent any subtle race conditions by wrapping a mutex lock around
627 MutexLock l(&log_mutex);
628 LogDestination::email_logging_severity_ = min_severity;
629 LogDestination::addresses_ = addresses;
632 static void ColoredWriteToStderr(LogSeverity severity,
633 const char* message, size_t len) {
634 const GLogColor color =
635 (LogDestination::terminal_supports_color() && FLAGS_colorlogtostderr) ?
636 SeverityToColor(severity) : COLOR_DEFAULT;
638 // Avoid using cerr from this module since we may get called during
639 // exit code, and cerr may be partially or fully destroyed by then.
640 if (COLOR_DEFAULT == color) {
641 fwrite(message, len, 1, stderr);
645 const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
647 // Gets the current text color.
648 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
649 GetConsoleScreenBufferInfo(stderr_handle, &buffer_info);
650 const WORD old_color_attrs = buffer_info.wAttributes;
652 // We need to flush the stream buffers into the console before each
653 // SetConsoleTextAttribute call lest it affect the text that is already
654 // printed but has not yet reached the console.
656 SetConsoleTextAttribute(stderr_handle,
657 GetColorAttribute(color) | FOREGROUND_INTENSITY);
658 fwrite(message, len, 1, stderr);
660 // Restores the text color.
661 SetConsoleTextAttribute(stderr_handle, old_color_attrs);
663 fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color));
664 fwrite(message, len, 1, stderr);
665 fprintf(stderr, "\033[m"); // Resets the terminal to default.
669 static void WriteToStderr(const char* message, size_t len) {
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 fwrite(message, len, 1, stderr);
675 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
676 const char* message, size_t len) {
677 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
678 ColoredWriteToStderr(severity, message, len);
680 // On Windows, also output to the debugger
681 ::OutputDebugStringA(string(message,len).c_str());
687 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
688 const char* message, size_t len) {
689 if (severity >= email_logging_severity_ ||
690 severity >= FLAGS_logemaillevel) {
691 string to(FLAGS_alsologtoemail);
692 if (!addresses_.empty()) {
698 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
699 glog_internal_namespace_::ProgramInvocationShortName());
700 string body(hostname());
702 body.append(message, len);
704 // should NOT use SendEmail(). The caller of this function holds the
705 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
706 // acquire the log_mutex object. Use SendEmailInternal() and set
707 // use_logging to false.
708 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
713 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
717 const bool should_flush = severity > FLAGS_logbuflevel;
718 LogDestination* destination = log_destination(severity);
719 destination->logger_->Write(should_flush, timestamp, message, len);
722 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
727 if ( FLAGS_logtostderr ) { // global flag: never log to file
728 ColoredWriteToStderr(severity, message, len);
730 for (int i = severity; i >= 0; --i)
731 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
735 inline void LogDestination::LogToSinks(LogSeverity severity,
736 const char *full_filename,
737 const char *base_filename,
739 const struct ::tm* tm_time,
741 size_t message_len) {
742 ReaderMutexLock l(&sink_mutex_);
744 for (int i = sinks_->size() - 1; i >= 0; i--) {
745 (*sinks_)[i]->send(severity, full_filename, base_filename,
746 line, tm_time, message, message_len);
751 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
752 ReaderMutexLock l(&sink_mutex_);
754 for (int i = sinks_->size() - 1; i >= 0; i--) {
755 (*sinks_)[i]->WaitTillSent();
758 const bool send_to_sink =
759 (data->send_method_ == &LogMessage::SendToSink) ||
760 (data->send_method_ == &LogMessage::SendToSinkAndLog);
761 if (send_to_sink && data->sink_ != NULL) {
762 data->sink_->WaitTillSent();
766 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
768 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
769 assert(severity >=0 && severity < NUM_SEVERITIES);
770 if (!log_destinations_[severity]) {
771 log_destinations_[severity] = new LogDestination(severity, NULL);
773 return log_destinations_[severity];
776 void LogDestination::DeleteLogDestinations() {
777 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
778 delete log_destinations_[severity];
779 log_destinations_[severity] = NULL;
785 LogFileObject::LogFileObject(LogSeverity severity,
786 const char* base_filename)
787 : base_filename_selected_(base_filename != NULL),
788 base_filename_((base_filename != NULL) ? base_filename : ""),
789 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
790 filename_extension_(),
793 bytes_since_flush_(0),
795 rollover_attempt_(kRolloverAttemptFrequency-1),
796 next_flush_time_(0) {
797 assert(severity >= 0);
798 assert(severity < NUM_SEVERITIES);
801 LogFileObject::~LogFileObject() {
809 void LogFileObject::SetBasename(const char* basename) {
811 base_filename_selected_ = true;
812 if (base_filename_ != basename) {
813 // Get rid of old log file since we are changing names
817 rollover_attempt_ = kRolloverAttemptFrequency-1;
819 base_filename_ = basename;
823 void LogFileObject::SetExtension(const char* ext) {
825 if (filename_extension_ != ext) {
826 // Get rid of old log file since we are changing names
830 rollover_attempt_ = kRolloverAttemptFrequency-1;
832 filename_extension_ = ext;
836 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
838 symlink_basename_ = symlink_basename;
841 void LogFileObject::Flush() {
846 void LogFileObject::FlushUnlocked(){
849 bytes_since_flush_ = 0;
851 // Figure out when we are due for another flush.
852 const int64 next = (FLAGS_logbufsecs
853 * static_cast<int64>(1000000)); // in usec
854 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
857 bool LogFileObject::CreateLogfile(const string& time_pid_string) {
858 string string_filename = base_filename_+filename_extension_+
860 const char* filename = string_filename.c_str();
861 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
862 if (fd == -1) return false;
864 // Mark the file close-on-exec. We don't really care if this fails
865 fcntl(fd, F_SETFD, FD_CLOEXEC);
868 file_ = fdopen(fd, "a"); // Make a FILE*.
869 if (file_ == NULL) { // Man, we're screwed!
871 unlink(filename); // Erase the half-baked evidence: an unusable log file
875 // We try to create a symlink called <program_name>.<severity>,
876 // which is easier to use. (Every time we create a new logfile,
877 // we destroy the old symlink and create a new one, so it always
878 // points to the latest logfile.) If it fails, we're sad but it's
880 if (!symlink_basename_.empty()) {
881 // take directory from filename
882 const char* slash = strrchr(filename, PATH_SEPARATOR);
883 const string linkname =
884 symlink_basename_ + '.' + LogSeverityNames[severity_];
886 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
887 linkpath += linkname;
888 unlink(linkpath.c_str()); // delete old one if it exists
890 // We must have unistd.h.
892 // Make the symlink be relative (in the same dir) so that if the
893 // entire log directory gets relocated the link is still valid.
894 const char *linkdest = slash ? (slash + 1) : filename;
895 if (symlink(linkdest, linkpath.c_str()) != 0) {
896 // silently ignore failures
899 // Make an additional link to the log file in a place specified by
900 // FLAGS_log_link, if indicated
901 if (!FLAGS_log_link.empty()) {
902 linkpath = FLAGS_log_link + "/" + linkname;
903 unlink(linkpath.c_str()); // delete old one if it exists
904 if (symlink(filename, linkpath.c_str()) != 0) {
905 // silently ignore failures
911 return true; // Everything worked
914 void LogFileObject::Write(bool force_flush,
920 // We don't log if the base_name_ is "" (which means "don't write")
921 if (base_filename_selected_ && base_filename_.empty()) {
925 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
927 if (file_ != NULL) fclose(file_);
929 file_length_ = bytes_since_flush_ = 0;
930 rollover_attempt_ = kRolloverAttemptFrequency-1;
933 // If there's no destination file, make one before outputting
935 // Try to rollover the log file every 32 log messages. The only time
936 // this could matter would be when we have trouble creating the log
937 // file. If that happens, we'll lose lots of log messages, of course!
938 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
939 rollover_attempt_ = 0;
942 localtime_r(×tamp, &tm_time);
944 // The logfile's filename will have the date/time & pid in it
945 ostringstream time_pid_stream;
946 time_pid_stream.fill('0');
947 time_pid_stream << 1900+tm_time.tm_year
948 << setw(2) << 1+tm_time.tm_mon
949 << setw(2) << tm_time.tm_mday
951 << setw(2) << tm_time.tm_hour
952 << setw(2) << tm_time.tm_min
953 << setw(2) << tm_time.tm_sec
955 << GetMainThreadPid();
956 const string& time_pid_string = time_pid_stream.str();
958 if (base_filename_selected_) {
959 if (!CreateLogfile(time_pid_string)) {
960 perror("Could not create log file");
961 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
962 time_pid_string.c_str());
966 // If no base filename for logs of this severity has been set, use a
967 // default base filename of
968 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
969 // logfiles will have names like
970 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
971 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
972 // and 4354 is the pid of the logging process. The date & time reflect
973 // when the file was created for output.
975 // Where does the file get put? Successively try the directories
977 string stripped_filename(
978 glog_internal_namespace_::ProgramInvocationShortName());
980 GetHostName(&hostname);
982 string uidname = MyUserName();
983 // We should not call CHECK() here because this function can be
984 // called after holding on to log_mutex. We don't want to
985 // attempt to hold on to the same mutex, and get into a
986 // deadlock. Simply use a name like invalid-user.
987 if (uidname.empty()) uidname = "invalid-user";
989 stripped_filename = stripped_filename+'.'+hostname+'.'
991 +LogSeverityNames[severity_]+'.';
992 // We're going to (potentially) try to put logs in several different dirs
993 const vector<string> & log_dirs = GetLoggingDirectories();
995 // Go through the list of dirs, and try to create the log file in each
996 // until we succeed or run out of options
997 bool success = false;
998 for (vector<string>::const_iterator dir = log_dirs.begin();
999 dir != log_dirs.end();
1001 base_filename_ = *dir + "/" + stripped_filename;
1002 if ( CreateLogfile(time_pid_string) ) {
1007 // If we never succeeded, we have to give up
1008 if ( success == false ) {
1009 perror("Could not create logging file");
1010 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
1011 time_pid_string.c_str());
1016 // Write a header message into the log file
1017 ostringstream file_header_stream;
1018 file_header_stream.fill('0');
1019 file_header_stream << "Log file created at: "
1020 << 1900+tm_time.tm_year << '/'
1021 << setw(2) << 1+tm_time.tm_mon << '/'
1022 << setw(2) << tm_time.tm_mday
1024 << setw(2) << tm_time.tm_hour << ':'
1025 << setw(2) << tm_time.tm_min << ':'
1026 << setw(2) << tm_time.tm_sec << '\n'
1027 << "Running on machine: "
1028 << LogDestination::hostname() << '\n'
1029 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
1030 << "threadid file:line] msg" << '\n';
1031 const string& file_header_string = file_header_stream.str();
1033 const int header_len = file_header_string.size();
1034 fwrite(file_header_string.data(), 1, header_len, file_);
1035 file_length_ += header_len;
1036 bytes_since_flush_ += header_len;
1039 // Write to LOG file
1040 if ( !stop_writing ) {
1041 // fwrite() doesn't return an error when the disk is full, for
1042 // messages that are less than 4096 bytes. When the disk is full,
1043 // it returns the message length for messages that are less than
1044 // 4096 bytes. fwrite() returns 4096 for message lengths that are
1045 // greater than 4096, thereby indicating an error.
1047 fwrite(message, 1, message_len, file_);
1048 if ( FLAGS_stop_logging_if_full_disk &&
1049 errno == ENOSPC ) { // disk full, stop writing to disk
1050 stop_writing = true; // until the disk is
1053 file_length_ += message_len;
1054 bytes_since_flush_ += message_len;
1057 if ( CycleClock_Now() >= next_flush_time_ )
1058 stop_writing = false; // check to see if disk has free space.
1059 return; // no need to flush
1062 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
1063 // or every "FLAGS_logbufsecs" seconds.
1065 (bytes_since_flush_ >= 1000000) ||
1066 (CycleClock_Now() >= next_flush_time_) ) {
1069 if (FLAGS_drop_log_memory) {
1070 if (file_length_ >= logging::kPageSize) {
1071 // don't evict the most recent page
1072 uint32 len = file_length_ & ~(logging::kPageSize - 1);
1073 posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
1082 // An arbitrary limit on the length of a single log message. This
1083 // is so that streaming can be done more efficiently.
1084 const size_t LogMessage::kMaxLogMessageLen = 30000;
1086 // Static log data space to avoid alloc failures in a LOG(FATAL)
1088 // Since multiple threads may call LOG(FATAL), and we want to preserve
1089 // the data from the first call, we allocate two sets of space. One
1090 // for exclusive use by the first thread, and one for shared use by
1091 // all other threads.
1092 static Mutex fatal_msg_lock;
1093 static CrashReason crash_reason;
1094 static bool fatal_msg_exclusive = true;
1095 static char fatal_msg_buf_exclusive[LogMessage::kMaxLogMessageLen+1];
1096 static char fatal_msg_buf_shared[LogMessage::kMaxLogMessageLen+1];
1097 static LogMessage::LogStream fatal_msg_stream_exclusive(
1098 fatal_msg_buf_exclusive, LogMessage::kMaxLogMessageLen, 0);
1099 static LogMessage::LogStream fatal_msg_stream_shared(
1100 fatal_msg_buf_shared, LogMessage::kMaxLogMessageLen, 0);
1101 static LogMessage::LogMessageData fatal_msg_data_exclusive;
1102 static LogMessage::LogMessageData fatal_msg_data_shared;
1104 LogMessage::LogMessageData::~LogMessageData() {
1106 delete stream_alloc_;
1109 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1110 int ctr, void (LogMessage::*send_method)())
1111 : allocated_(NULL) {
1112 Init(file, line, severity, send_method);
1113 data_->stream_->set_ctr(ctr);
1116 LogMessage::LogMessage(const char* file, int line,
1117 const CheckOpString& result)
1118 : allocated_(NULL) {
1119 Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
1120 stream() << "Check failed: " << (*result.str_) << " ";
1123 LogMessage::LogMessage(const char* file, int line)
1124 : allocated_(NULL) {
1125 Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
1128 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
1129 : allocated_(NULL) {
1130 Init(file, line, severity, &LogMessage::SendToLog);
1133 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1134 LogSink* sink, bool also_send_to_log)
1135 : allocated_(NULL) {
1136 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
1137 &LogMessage::SendToSink);
1138 data_->sink_ = sink; // override Init()'s setting to NULL
1141 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1142 vector<string> *outvec)
1143 : allocated_(NULL) {
1144 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
1145 data_->outvec_ = outvec; // override Init()'s setting to NULL
1148 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1150 : allocated_(NULL) {
1151 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
1152 data_->message_ = message; // override Init()'s setting to NULL
1155 void LogMessage::Init(const char* file,
1157 LogSeverity severity,
1158 void (LogMessage::*send_method)()) {
1160 if (severity != GLOG_FATAL || !exit_on_dfatal) {
1161 allocated_ = new LogMessageData();
1163 data_->buf_ = new char[kMaxLogMessageLen+1];
1164 data_->message_text_ = data_->buf_;
1165 data_->stream_alloc_ =
1166 new LogStream(data_->message_text_, kMaxLogMessageLen, 0);
1167 data_->stream_ = data_->stream_alloc_;
1168 data_->first_fatal_ = false;
1170 MutexLock l(&fatal_msg_lock);
1171 if (fatal_msg_exclusive) {
1172 fatal_msg_exclusive = false;
1173 data_ = &fatal_msg_data_exclusive;
1174 data_->message_text_ = fatal_msg_buf_exclusive;
1175 data_->stream_ = &fatal_msg_stream_exclusive;
1176 data_->first_fatal_ = true;
1178 data_ = &fatal_msg_data_shared;
1179 data_->message_text_ = fatal_msg_buf_shared;
1180 data_->stream_ = &fatal_msg_stream_shared;
1181 data_->first_fatal_ = false;
1183 data_->stream_alloc_ = NULL;
1187 data_->preserved_errno_ = errno;
1188 data_->severity_ = severity;
1189 data_->line_ = line;
1190 data_->send_method_ = send_method;
1191 data_->sink_ = NULL;
1192 data_->outvec_ = NULL;
1193 WallTime now = WallTime_Now();
1194 data_->timestamp_ = static_cast<time_t>(now);
1195 localtime_r(&data_->timestamp_, &data_->tm_time_);
1196 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1197 RawLog__SetLastTime(data_->tm_time_, usecs);
1199 data_->num_chars_to_log_ = 0;
1200 data_->num_chars_to_syslog_ = 0;
1201 data_->basename_ = const_basename(file);
1202 data_->fullname_ = file;
1203 data_->has_been_flushed_ = false;
1205 // If specified, prepend a prefix to each line. For example:
1206 // I1018 160715 f5d4fbb0 logging.cc:1153]
1207 // (log level, GMT month, date, time, thread_id, file basename, line)
1208 // We exclude the thread_id for the default thread.
1209 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1210 stream() << LogSeverityNames[severity][0]
1211 << setw(2) << 1+data_->tm_time_.tm_mon
1212 << setw(2) << data_->tm_time_.tm_mday
1214 << setw(2) << data_->tm_time_.tm_hour << ':'
1215 << setw(2) << data_->tm_time_.tm_min << ':'
1216 << setw(2) << data_->tm_time_.tm_sec << "."
1219 << setfill(' ') << setw(5)
1220 << static_cast<unsigned int>(GetTID()) << setfill('0')
1222 << data_->basename_ << ':' << data_->line_ << "] ";
1224 data_->num_prefix_chars_ = data_->stream_->pcount();
1226 if (!FLAGS_log_backtrace_at.empty()) {
1228 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1229 #ifdef HAVE_STACKTRACE
1230 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1232 DumpStackTraceToString(&stacktrace);
1233 stream() << " (stacktrace:\n" << stacktrace << ") ";
1239 LogMessage::~LogMessage() {
1244 int LogMessage::preserved_errno() const {
1245 return data_->preserved_errno_;
1248 ostream& LogMessage::stream() {
1249 return *(data_->stream_);
1252 // Flush buffered message, called by the destructor, or any other function
1253 // that needs to synchronize the log.
1254 void LogMessage::Flush() {
1255 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1258 data_->num_chars_to_log_ = data_->stream_->pcount();
1259 data_->num_chars_to_syslog_ =
1260 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1262 // Do we need to add a \n to the end of this message?
1263 bool append_newline =
1264 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1265 char original_final_char = '\0';
1267 // If we do need to add a \n, we'll do it by violating the memory of the
1268 // ostrstream buffer. This is quick, and we'll make sure to undo our
1269 // modification before anything else is done with the ostrstream. It
1270 // would be preferable not to do things this way, but it seems to be
1271 // the best way to deal with this.
1272 if (append_newline) {
1273 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1274 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1277 // Prevent any subtle race conditions by wrapping a mutex lock around
1278 // the actual logging action per se.
1280 MutexLock l(&log_mutex);
1281 (this->*(data_->send_method_))();
1282 ++num_messages_[static_cast<int>(data_->severity_)];
1284 LogDestination::WaitForSinks(data_);
1286 if (append_newline) {
1287 // Fix the ostrstream back how it was before we screwed with it.
1288 // It's 99.44% certain that we don't need to worry about doing this.
1289 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1292 // If errno was already set before we enter the logging call, we'll
1293 // set it back to that value when we return from the logging call.
1294 // It happens often that we log an error message after a syscall
1295 // failure, which can potentially set the errno to some other
1296 // values. We would like to preserve the original errno.
1297 if (data_->preserved_errno_ != 0) {
1298 errno = data_->preserved_errno_;
1301 // Note that this message is now safely logged. If we're asked to flush
1302 // again, as a result of destruction, say, we'll do nothing on future calls.
1303 data_->has_been_flushed_ = true;
1306 // Copy of first FATAL log message so that we can print it out again
1307 // after all the stack traces. To preserve legacy behavior, we don't
1308 // use fatal_msg_buf_exclusive.
1309 static time_t fatal_time;
1310 static char fatal_message[256];
1312 void ReprintFatalMessage() {
1313 if (fatal_message[0]) {
1314 const int n = strlen(fatal_message);
1315 if (!FLAGS_logtostderr) {
1316 // Also write to stderr (don't color to avoid terminal checks)
1317 WriteToStderr(fatal_message, n);
1319 LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1323 // L >= log_mutex (callers must hold the log_mutex).
1324 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1325 static bool already_warned_before_initgoogle = false;
1327 log_mutex.AssertHeld();
1329 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1330 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1332 // Messages of a given severity get logged to lower severity logs, too
1334 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1335 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1336 "written to STDERR\n";
1337 WriteToStderr(w, strlen(w));
1338 already_warned_before_initgoogle = true;
1341 // global flag: never log to file if set. Also -- don't log to a
1342 // file if we haven't parsed the command line flags to get the
1344 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1345 ColoredWriteToStderr(data_->severity_,
1346 data_->message_text_, data_->num_chars_to_log_);
1348 // this could be protected by a flag if necessary.
1349 LogDestination::LogToSinks(data_->severity_,
1350 data_->fullname_, data_->basename_,
1351 data_->line_, &data_->tm_time_,
1352 data_->message_text_ + data_->num_prefix_chars_,
1353 (data_->num_chars_to_log_ -
1354 data_->num_prefix_chars_ - 1));
1357 // log this message to all log files of severity <= severity_
1358 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1359 data_->message_text_,
1360 data_->num_chars_to_log_);
1362 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1363 data_->num_chars_to_log_);
1364 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1365 data_->num_chars_to_log_);
1366 LogDestination::LogToSinks(data_->severity_,
1367 data_->fullname_, data_->basename_,
1368 data_->line_, &data_->tm_time_,
1369 data_->message_text_ + data_->num_prefix_chars_,
1370 (data_->num_chars_to_log_
1371 - data_->num_prefix_chars_ - 1));
1372 // NOTE: -1 removes trailing \n
1375 // If we log a FATAL message, flush all the log destinations, then toss
1376 // a signal for others to catch. We leave the logs in a state that
1377 // someone else can use them (as long as they flush afterwards)
1378 if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1379 if (data_->first_fatal_) {
1380 // Store crash information so that it is accessible from within signal
1381 // handlers that may be invoked later.
1382 RecordCrashReason(&crash_reason);
1383 SetCrashReason(&crash_reason);
1385 // Store shortened fatal message for other logs and GWQ status
1386 const int copy = min<int>(data_->num_chars_to_log_,
1387 sizeof(fatal_message)-1);
1388 memcpy(fatal_message, data_->message_text_, copy);
1389 fatal_message[copy] = '\0';
1390 fatal_time = data_->timestamp_;
1393 if (!FLAGS_logtostderr) {
1394 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1395 if ( LogDestination::log_destinations_[i] )
1396 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1400 // release the lock that our caller (directly or indirectly)
1401 // LogMessage::~LogMessage() grabbed so that signal handlers
1402 // can use the logging facility. Alternately, we could add
1403 // an entire unsafe logging interface to bypass locking
1404 // for signal handlers but this seems simpler.
1406 LogDestination::WaitForSinks(data_);
1408 const char* message = "*** Check failure stack trace: ***\n";
1409 if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1416 void LogMessage::RecordCrashReason(
1417 glog_internal_namespace_::CrashReason* reason) {
1418 reason->filename = fatal_msg_data_exclusive.fullname_;
1419 reason->line_number = fatal_msg_data_exclusive.line_;
1420 reason->message = fatal_msg_buf_exclusive +
1421 fatal_msg_data_exclusive.num_prefix_chars_;
1422 #ifdef HAVE_STACKTRACE
1423 // Retrieve the stack trace, omitting the logging frames that got us here.
1424 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1430 #ifdef HAVE___ATTRIBUTE__
1431 # define ATTRIBUTE_NORETURN __attribute__((noreturn))
1433 # define ATTRIBUTE_NORETURN
1436 static void logging_fail() ATTRIBUTE_NORETURN;
1438 static void logging_fail() {
1439 #if defined(_DEBUG) && defined(_MSC_VER)
1440 // When debugging on windows, avoid the obnoxious dialog and make
1441 // it possible to continue past a LOG(FATAL) in the debugger
1448 typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN;
1450 GOOGLE_GLOG_DLL_DECL
1451 logging_fail_func_t g_logging_fail_func = &logging_fail;
1453 void InstallFailureFunction(void (*fail_func)()) {
1454 g_logging_fail_func = (logging_fail_func_t)fail_func;
1457 void LogMessage::Fail() {
1458 g_logging_fail_func();
1461 // L >= log_mutex (callers must hold the log_mutex).
1462 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1463 if (data_->sink_ != NULL) {
1464 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1465 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1466 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1467 data_->line_, &data_->tm_time_,
1468 data_->message_text_ + data_->num_prefix_chars_,
1469 (data_->num_chars_to_log_ -
1470 data_->num_prefix_chars_ - 1));
1474 // L >= log_mutex (callers must hold the log_mutex).
1475 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1480 // L >= log_mutex (callers must hold the log_mutex).
1481 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1482 if (data_->outvec_ != NULL) {
1483 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1484 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1485 // Omit prefix of message and trailing newline when recording in outvec_.
1486 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1487 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1488 data_->outvec_->push_back(string(start, len));
1494 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1495 if (data_->message_ != NULL) {
1496 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1497 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1498 // Omit prefix of message and trailing newline when writing to message_.
1499 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1500 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1501 data_->message_->assign(start, len);
1506 // L >= log_mutex (callers must hold the log_mutex).
1507 void LogMessage::SendToSyslogAndLog() {
1508 #ifdef HAVE_SYSLOG_H
1509 // Before any calls to syslog(), make a single call to openlog()
1510 static bool openlog_already_called = false;
1511 if (!openlog_already_called) {
1512 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1513 LOG_CONS | LOG_NDELAY | LOG_PID,
1515 openlog_already_called = true;
1518 // This array maps Google severity levels to syslog levels
1519 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1520 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1521 int(data_->num_chars_to_syslog_),
1522 data_->message_text_ + data_->num_prefix_chars_);
1525 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1529 base::Logger* base::GetLogger(LogSeverity severity) {
1530 MutexLock l(&log_mutex);
1531 return LogDestination::log_destination(severity)->logger_;
1534 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1535 MutexLock l(&log_mutex);
1536 LogDestination::log_destination(severity)->logger_ = logger;
1539 // L < log_mutex. Acquires and releases mutex_.
1540 int64 LogMessage::num_messages(int severity) {
1541 MutexLock l(&log_mutex);
1542 return num_messages_[severity];
1545 // Output the COUNTER value. This is only valid if ostream is a
1547 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1549 LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
1551 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1553 CHECK(log && log == log->self())
1554 << "You must not use COUNTER with non-glog ostream";
1559 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1560 LogSeverity severity, int ctr,
1561 void (LogMessage::*send_method)())
1562 : LogMessage(file, line, severity, ctr, send_method) {
1565 ErrnoLogMessage::~ErrnoLogMessage() {
1566 // Don't access errno directly because it may have been altered
1567 // while streaming the message.
1569 posix_strerror_r(preserved_errno(), buf, sizeof(buf));
1570 stream() << ": " << buf << " [" << preserved_errno() << "]";
1573 void FlushLogFiles(LogSeverity min_severity) {
1574 LogDestination::FlushLogFiles(min_severity);
1577 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1578 LogDestination::FlushLogFilesUnsafe(min_severity);
1581 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1582 LogDestination::SetLogDestination(severity, base_filename);
1585 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1586 LogDestination::SetLogSymlink(severity, symlink_basename);
1589 LogSink::~LogSink() {
1592 void LogSink::WaitTillSent() {
1596 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1597 const struct ::tm* tm_time,
1598 const char* message, size_t message_len) {
1599 ostringstream stream(string(message, message_len));
1602 // FIXME(jrvb): Updating this to use the correct value for usecs
1603 // requires changing the signature for both this method and
1604 // LogSink::send(). This change needs to be done in a separate CL
1605 // so subclasses of LogSink can be updated at the same time.
1608 stream << LogSeverityNames[severity][0]
1609 << setw(2) << 1+tm_time->tm_mon
1610 << setw(2) << tm_time->tm_mday
1612 << setw(2) << tm_time->tm_hour << ':'
1613 << setw(2) << tm_time->tm_min << ':'
1614 << setw(2) << tm_time->tm_sec << '.'
1617 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1619 << file << ':' << line << "] ";
1621 stream << string(message, message_len);
1622 return stream.str();
1625 void AddLogSink(LogSink *destination) {
1626 LogDestination::AddLogSink(destination);
1629 void RemoveLogSink(LogSink *destination) {
1630 LogDestination::RemoveLogSink(destination);
1633 void SetLogFilenameExtension(const char* ext) {
1634 LogDestination::SetLogFilenameExtension(ext);
1637 void SetStderrLogging(LogSeverity min_severity) {
1638 LogDestination::SetStderrLogging(min_severity);
1641 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1642 LogDestination::SetEmailLogging(min_severity, addresses);
1645 void LogToStderr() {
1646 LogDestination::LogToStderr();
1650 namespace internal {
1652 bool GetExitOnDFatal() {
1653 MutexLock l(&log_mutex);
1654 return exit_on_dfatal;
1657 // Determines whether we exit the program for a LOG(DFATAL) message in
1658 // debug mode. It does this by skipping the call to Fail/FailQuietly.
1659 // This is intended for testing only.
1661 // This can have some effects on LOG(FATAL) as well. Failure messages
1662 // are always allocated (rather than sharing a buffer), the crash
1663 // reason is not recorded, the "gwq" status message is not updated,
1664 // and the stack trace is not recorded. The LOG(FATAL) *will* still
1665 // exit the program. Since this function is used only in testing,
1666 // these differences are acceptable.
1667 void SetExitOnDFatal(bool value) {
1668 MutexLock l(&log_mutex);
1669 exit_on_dfatal = value;
1672 } // namespace internal
1675 // use_logging controls whether the logging functions LOG/VLOG are used
1676 // to log errors. It should be set to false when the caller holds the
1678 static bool SendEmailInternal(const char*dest, const char *subject,
1679 const char*body, bool use_logging) {
1680 if (dest && *dest) {
1681 if ( use_logging ) {
1682 VLOG(1) << "Trying to send TITLE:" << subject
1683 << " BODY:" << body << " to " << dest;
1685 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1686 subject, body, dest);
1690 FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1691 FILE* pipe = popen(cmd.c_str(), "w");
1693 // Add the body if we have one
1695 fwrite(body, sizeof(char), strlen(body), pipe);
1696 bool ok = pclose(pipe) != -1;
1698 if ( use_logging ) {
1700 posix_strerror_r(errno, buf, sizeof(buf));
1701 LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf;
1704 posix_strerror_r(errno, buf, sizeof(buf));
1705 fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf);
1710 if ( use_logging ) {
1711 LOG(ERROR) << "Unable to send mail to " << dest;
1713 fprintf(stderr, "Unable to send mail to %s\n", dest);
1720 bool SendEmail(const char*dest, const char *subject, const char*body){
1721 return SendEmailInternal(dest, subject, body, true);
1724 static void GetTempDirectories(vector<string>* list) {
1727 // On windows we'll try to find a directory in this order:
1728 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1731 // C:/WINDOWS/ or C:/WINNT/
1734 if (GetTempPathA(MAX_PATH, tmp))
1735 list->push_back(tmp);
1736 list->push_back("C:\\tmp\\");
1737 list->push_back("C:\\temp\\");
1739 // Directories, in order of preference. If we find a dir that
1740 // exists, we stop adding other less-preferred dirs
1741 const char * candidates[] = {
1742 // Non-null only during unittest/regtest
1743 getenv("TEST_TMPDIR"),
1745 // Explicitly-supplied temp dirs
1746 getenv("TMPDIR"), getenv("TMP"),
1748 // If all else fails
1752 for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
1753 const char *d = candidates[i];
1754 if (!d) continue; // Empty env var
1756 // Make sure we don't surprise anyone who's expecting a '/'
1758 if (dstr[dstr.size() - 1] != '/') {
1761 list->push_back(dstr);
1763 struct stat statbuf;
1764 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1765 // We found a dir that exists - we're done.
1773 static vector<string>* logging_directories_list;
1775 const vector<string>& GetLoggingDirectories() {
1776 // Not strictly thread-safe but we're called early in InitGoogle().
1777 if (logging_directories_list == NULL) {
1778 logging_directories_list = new vector<string>;
1780 if ( !FLAGS_log_dir.empty() ) {
1781 // A dir was specified, we should use it
1782 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1784 GetTempDirectories(logging_directories_list);
1787 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1788 logging_directories_list->push_back(tmp);
1789 logging_directories_list->push_back(".\\");
1791 logging_directories_list->push_back("./");
1795 return *logging_directories_list;
1798 void TestOnly_ClearLoggingDirectoriesList() {
1799 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1800 "called from test code.\n");
1801 delete logging_directories_list;
1802 logging_directories_list = NULL;
1805 void GetExistingTempDirectories(vector<string>* list) {
1806 GetTempDirectories(list);
1807 vector<string>::iterator i_dir = list->begin();
1808 while( i_dir != list->end() ) {
1809 // zero arg to access means test for existence; no constant
1810 // defined on windows
1811 if ( access(i_dir->c_str(), 0) ) {
1812 i_dir = list->erase(i_dir);
1819 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1820 #ifdef HAVE_UNISTD_H
1821 struct stat statbuf;
1822 const int kCopyBlockSize = 8 << 10;
1823 char copybuf[kCopyBlockSize];
1824 int64 read_offset, write_offset;
1825 // Don't follow symlinks unless they're our own fd symlinks in /proc
1827 const char *procfd_prefix = "/proc/self/fd/";
1828 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1830 int fd = open(path, flags);
1832 if (errno == EFBIG) {
1833 // The log file in question has got too big for us to open. The
1834 // real fix for this would be to compile logging.cc (or probably
1835 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1837 // Instead just truncate the file to something we can manage
1838 if (truncate(path, 0) == -1) {
1839 PLOG(ERROR) << "Unable to truncate " << path;
1841 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1844 PLOG(ERROR) << "Unable to open " << path;
1849 if (fstat(fd, &statbuf) == -1) {
1850 PLOG(ERROR) << "Unable to fstat()";
1854 // See if the path refers to a regular file bigger than the
1856 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1857 if (statbuf.st_size <= limit) goto out_close_fd;
1858 if (statbuf.st_size <= keep) goto out_close_fd;
1860 // This log file is too large - we need to truncate it
1861 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1863 // Copy the last "keep" bytes of the file to the beginning of the file
1864 read_offset = statbuf.st_size - keep;
1866 int bytesin, bytesout;
1867 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1868 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1869 if (bytesout == -1) {
1870 PLOG(ERROR) << "Unable to write to " << path;
1872 } else if (bytesout != bytesin) {
1873 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1875 read_offset += bytesin;
1876 write_offset += bytesout;
1878 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1880 // Truncate the remainder of the file. If someone else writes to the
1881 // end of the file after our last read() above, we lose their latest
1882 // data. Too bad ...
1883 if (ftruncate(fd, write_offset) == -1) {
1884 PLOG(ERROR) << "Unable to truncate " << path;
1890 LOG(ERROR) << "No log truncation support.";
1894 void TruncateStdoutStderr() {
1895 #ifdef HAVE_UNISTD_H
1896 int64 limit = MaxLogSize() << 20;
1897 int64 keep = 1 << 20;
1898 TruncateLogFile("/proc/self/fd/1", limit, keep);
1899 TruncateLogFile("/proc/self/fd/2", limit, keep);
1901 LOG(ERROR) << "No log truncation support.";
1906 // Helper functions for string comparisons.
1907 #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
1908 string* Check##func##expected##Impl(const char* s1, const char* s2, \
1909 const char* names) { \
1910 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
1911 if (equal == expected) return NULL; \
1916 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1917 return new string(ss.str()); \
1920 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1921 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1922 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1923 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1924 #undef DEFINE_CHECK_STROP_IMPL
1926 int posix_strerror_r(int err, char *buf, size_t len) {
1927 // Sanity check input parameters
1928 if (buf == NULL || len <= 0) {
1933 // Reset buf and errno, and try calling whatever version of strerror_r()
1934 // is implemented by glibc
1936 int old_errno = errno;
1938 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1940 // Both versions set errno on failure
1942 // Should already be there, but better safe than sorry
1948 // POSIX is vague about whether the string will be terminated, although
1949 // is indirectly implies that typically ERANGE will be returned, instead
1950 // of truncating the string. This is different from the GNU implementation.
1951 // We play it safe by always terminating the string explicitly.
1952 buf[len-1] = '\000';
1954 // If the function succeeded, we can use its exit code to determine the
1955 // semantics implemented by glibc
1959 // GNU semantics detected
1964 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
1965 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
1966 // This means an error on MacOSX or FreeBSD.
1970 strncat(buf, rc, len-1);
1976 LogMessageFatal::LogMessageFatal(const char* file, int line) :
1977 LogMessage(file, line, GLOG_FATAL) {}
1979 LogMessageFatal::LogMessageFatal(const char* file, int line,
1980 const CheckOpString& result) :
1981 LogMessage(file, line, result) {}
1983 LogMessageFatal::~LogMessageFatal() {
1990 CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
1991 : stream_(new ostringstream) {
1992 *stream_ << exprtext << " (";
1995 CheckOpMessageBuilder::~CheckOpMessageBuilder() {
1999 ostream* CheckOpMessageBuilder::ForVar2() {
2000 *stream_ << " vs. ";
2004 string* CheckOpMessageBuilder::NewString() {
2006 return new string(stream_->str());
2012 void MakeCheckOpValueString(std::ostream* os, const char& v) {
2013 if (v >= 32 && v <= 126) {
2014 (*os) << "'" << v << "'";
2016 (*os) << "char value " << (short)v;
2021 void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
2022 if (v >= 32 && v <= 126) {
2023 (*os) << "'" << v << "'";
2025 (*os) << "signed char value " << (short)v;
2030 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
2031 if (v >= 32 && v <= 126) {
2032 (*os) << "'" << v << "'";
2034 (*os) << "unsigned char value " << (unsigned short)v;
2038 void InitGoogleLogging(const char* argv0) {
2039 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
2042 void ShutdownGoogleLogging() {
2043 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
2044 LogDestination::DeleteLogDestinations();
2045 delete logging_directories_list;
2046 logging_directories_list = NULL;
2049 _END_GOOGLE_NAMESPACE_