Define ARRAYSIZE in utilities.h and use it.
[platform/upstream/glog.git] / src / logging.cc
1 #define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite()
2
3 #include "utilities.h"
4
5 #include <assert.h>
6 #include <iomanip>
7 #include <string>
8 #ifdef HAVE_UNISTD_H
9 # include <unistd.h>  // For _exit.
10 #endif
11 #include <climits>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #ifdef HAVE_SYS_UTSNAME_H
15 # include <sys/utsname.h>  // For uname.
16 #endif
17 #include <fcntl.h>
18 #include <cstdio>
19 #include <iostream>
20 #include <stdarg.h>
21 #include <stdlib.h>
22 #ifdef HAVE_PWD_H
23 # include <pwd.h>
24 #endif
25 #ifdef HAVE_SYSLOG_H
26 # include <syslog.h>
27 #endif
28 #include <vector>
29 #include <errno.h>                   // for errno
30 #include <sstream>
31 #include "base/commandlineflags.h"        // to get the program name
32 #include "glog/logging.h"
33 #include "glog/raw_logging.h"
34 #include "base/googleinit.h"
35
36 using std::string;
37 using std::vector;
38 using std::ostrstream;
39 using std::setw;
40 using std::hex;
41 using std::dec;
42 using std::min;
43 using std::ostream;
44 using std::ostringstream;
45 using std::strstream;
46
47 DEFINE_bool(logtostderr, false,
48             "log messages go to stderr instead of logfiles");
49 DEFINE_bool(alsologtostderr, false,
50             "log messages go to stderr in addition to logfiles");
51
52 // By default, errors (including fatal errors) get logged to stderr as
53 // well as the file.
54 //
55 // The default is ERROR instead of FATAL so that users can see problems
56 // when they run a program without having to look in another file.
57 DEFINE_int32(stderrthreshold,
58              GOOGLE_NAMESPACE::ERROR,
59              "log messages at or above this level are copied to stderr in "
60              "addition to logfiles.  This flag obsoletes --alsologtostderr.");
61
62 DEFINE_string(alsologtoemail, "",
63               "log messages go to these email addresses "
64               "in addition to logfiles");
65 DEFINE_bool(log_prefix, true,
66             "Prepend the log prefix to the start of each log line");
67 DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
68              "actually get logged anywhere");
69 DEFINE_int32(logbuflevel, 0,
70              "Buffer log messages logged at this level or lower"
71              " (-1 means don't buffer; 0 means buffer INFO only;"
72              " ...)");
73 DEFINE_int32(logbufsecs, 30,
74              "Buffer log messages for at most this many seconds");
75 DEFINE_int32(logemaillevel, 999,
76              "Email log messages logged at this level or higher"
77              " (0 means email all; 3 means email FATAL only;"
78              " ...)");
79 DEFINE_string(logmailer, "/bin/mail",
80               "Mailer used to send logging email");
81
82 // Compute the default value for --log_dir
83 static const char* DefaultLogDir() {
84   const char* env;
85   env = getenv("GOOGLE_LOG_DIR");
86   if (env != NULL && env[0] != '\0') {
87     return env;
88   }
89   env = getenv("TEST_TMPDIR");
90   if (env != NULL && env[0] != '\0') {
91     return env;
92   }
93   return "";
94 }
95
96 DEFINE_string(log_dir, DefaultLogDir(),
97               "If specified, logfiles are written into this directory instead "
98               "of the default logging directory.");
99 DEFINE_string(log_link, "", "Put additional links to the log "
100               "files in this directory");
101
102 DEFINE_int32(max_log_size, 1800,
103              "approx. maximum log file size (in MB)");
104
105 DEFINE_bool(stop_logging_if_full_disk, false,
106             "Stop attempting to log to disk if the disk is full.");
107
108 // TODO(hamaji): consider windows
109 #define PATH_SEPARATOR '/'
110
111 static void GetHostName(string* hostname) {
112 #if defined(HAVE_SYS_UTSNAME_H)
113   struct utsname buf;
114   if (0 != uname(&buf)) {
115     // ensure null termination on failure
116     *buf.nodename = '\0';
117   }
118   *hostname = buf.nodename;
119 #elif defined(OS_WINDOWS)
120   char buf[256];
121   DWORD len;
122   if (GetComputerNameA(buf, &len)) {
123     *hostname = buf;
124   } else {
125     hostname->clear();
126   }
127 #else
128 # warning There is no way to retrieve the host name.
129   *hostname = "(unknown)";
130 #endif
131 }
132
133 _START_GOOGLE_NAMESPACE_
134
135 // A mutex that allows only one thread to log at a time, to keep things from
136 // getting jumbled.  Some other very uncommon logging operations (like
137 // changing the destination file for log messages of a given severity) also
138 // lock this mutex.  Please be sure that anybody who might possibly need to
139 // lock it does so.
140 static Mutex log_mutex;
141
142 // Number of messages sent at each severity.  Under log_mutex.
143 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
144
145 // Globally disable log writing (if disk is full)
146 static bool stop_writing = false;
147
148 const char*const LogSeverityNames[NUM_SEVERITIES] = {
149   "INFO", "WARNING", "ERROR", "FATAL"
150 };
151
152 const char* GetLogSeverityName(LogSeverity severity) {
153   return LogSeverityNames[severity];
154 }
155
156 static bool SendEmailInternal(const char*dest, const char *subject,
157                               const char*body, bool use_logging);
158
159 base::Logger::~Logger() {
160 }
161
162 namespace {
163
164 // Encapsulates all file-system related state
165 class LogFileObject : public base::Logger {
166  public:
167   LogFileObject(LogSeverity severity, const char* base_filename);
168   ~LogFileObject();
169
170   virtual void Write(bool force_flush, // Should we force a flush here?
171                      time_t timestamp,  // Timestamp for this entry
172                      const char* message,
173                      int message_len);
174
175   // Configuration options
176   void SetBasename(const char* basename);
177   void SetExtension(const char* ext);
178   void SetSymlinkBasename(const char* symlink_basename);
179
180   // Normal flushing routine
181   virtual void Flush();
182
183   // It is the actual file length for the system loggers,
184   // i.e., INFO, ERROR, etc.
185   virtual uint32 LogSize() {
186     MutexLock l(&lock_);
187     return file_length_;
188   }
189
190   // Internal flush routine.  Exposed so that FlushLogFilesUnsafe()
191   // can avoid grabbing a lock.  Usually Flush() calls it after
192   // acquiring lock_.
193   void FlushUnlocked();
194
195  private:
196   static const uint32 kRolloverAttemptFrequency = 0x20;
197
198   Mutex lock_;
199   bool base_filename_selected_;
200   string base_filename_;
201   string symlink_basename_;
202   string filename_extension_;     // option users can specify (eg to add port#)
203   FILE* file_;
204   LogSeverity severity_;
205   uint32 bytes_since_flush_;
206   uint32 file_length_;
207   unsigned int rollover_attempt_;
208   int64 next_flush_time_;         // cycle count at which to flush log
209
210   // Actually create a logfile using the value of base_filename_ and the
211   // supplied argument time_pid_string
212   // REQUIRES: lock_ is held
213   bool CreateLogfile(const char* time_pid_string);
214 };
215
216 }  // namespace
217
218 class LogDestination {
219  public:
220   friend class LogMessage;
221   friend void ReprintFatalMessage();
222   friend base::Logger* base::GetLogger(LogSeverity);
223   friend void base::SetLogger(LogSeverity, base::Logger*);
224
225   // These methods are just forwarded to by their global versions.
226   static void SetLogDestination(LogSeverity severity,
227                                 const char* base_filename);
228   static void SetLogSymlink(LogSeverity severity,
229                             const char* symlink_basename);
230   static void AddLogSink(LogSink *destination);
231   static void RemoveLogSink(LogSink *destination);
232   static void SetLogFilenameExtension(const char* filename_extension);
233   static void SetStderrLogging(LogSeverity min_severity);
234   static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
235   static void LogToStderr();
236   // Flush all log files that are at least at the given severity level
237   static void FlushLogFiles(int min_severity);
238   static void FlushLogFilesUnsafe(int min_severity);
239
240   // we set the maximum size of our packet to be 1400, the logic being
241   // to prevent fragmentation.
242   // Really this number is arbitrary.
243   static const int kNetworkBytes = 1400;
244
245   static const string& hostname();
246  private:
247
248   LogDestination(LogSeverity severity, const char* base_filename);
249   ~LogDestination() { }
250
251   // Take a log message of a particular severity and log it to stderr
252   // iff it's of a high enough severity to deserve it.
253   static void MaybeLogToStderr(LogSeverity severity, const char* message,
254                                size_t len);
255
256   // Take a log message of a particular severity and log it to email
257   // iff it's of a high enough severity to deserve it.
258   static void MaybeLogToEmail(LogSeverity severity, const char* message,
259                               size_t len);
260   // Take a log message of a particular severity and log it to a file
261   // iff the base filename is not "" (which means "don't log to me")
262   static void MaybeLogToLogfile(LogSeverity severity,
263                                 time_t timestamp,
264                                 const char* message, size_t len);
265   // Take a log message of a particular severity and log it to the file
266   // for that severity and also for all files with severity less than
267   // this severity.
268   static void LogToAllLogfiles(LogSeverity severity,
269                                time_t timestamp,
270                                const char* message, size_t len);
271
272   // Send logging info to all registered sinks.
273   static void LogToSinks(LogSeverity severity,
274                          const char *full_filename,
275                          const char *base_filename,
276                          int line,
277                          const struct ::tm* tm_time,
278                          const char* message,
279                          size_t message_len);
280
281   // Wait for all registered sinks via WaitTillSent
282   // including the optional one in "data".
283   static void WaitForSinks(LogMessage::LogMessageData* data);
284
285   static LogDestination* log_destination(LogSeverity severity);
286
287   LogFileObject fileobject_;
288   base::Logger* logger_;      // Either &fileobject_, or wrapper around it
289
290   static LogDestination* log_destinations_[NUM_SEVERITIES];
291   static LogSeverity email_logging_severity_;
292   static string addresses_;
293   static string hostname_;
294
295   // arbitrary global logging destinations.
296   static vector<LogSink*>* sinks_;
297
298   // Protects the vector sinks_,
299   // but not the LogSink objects its elements reference.
300   static Mutex sink_mutex_;
301
302   // Disallow
303   LogDestination(const LogDestination&);
304   LogDestination& operator=(const LogDestination&);
305 };
306
307 // Errors do not get logged to email by default.
308 LogSeverity LogDestination::email_logging_severity_ = 99999;
309
310 string LogDestination::addresses_ = "";
311 string LogDestination::hostname_ = "";
312
313 vector<LogSink*>* LogDestination::sinks_ = NULL;
314 Mutex LogDestination::sink_mutex_;
315
316 /* static */
317 const string& LogDestination::hostname() {
318   if (hostname_.empty()) {
319     GetHostName(&hostname_);
320     if (hostname_.empty()) {
321       hostname_ = "(unknown)";
322     }
323   }
324   return hostname_;
325 }
326
327 LogDestination::LogDestination(LogSeverity severity,
328                                const char* base_filename)
329   : fileobject_(severity, base_filename),
330     logger_(&fileobject_) {
331 }
332
333 inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
334   // assume we have the log_mutex or we simply don't care
335   // about it
336   for (int i = min_severity; i < NUM_SEVERITIES; i++) {
337     LogDestination* log = log_destination(i);
338     if (log != NULL) {
339       // Flush the base fileobject_ logger directly instead of going
340       // through any wrappers to reduce chance of deadlock.
341       log->fileobject_.FlushUnlocked();
342     }
343   }
344 }
345
346 inline void LogDestination::FlushLogFiles(int min_severity) {
347   // Prevent any subtle race conditions by wrapping a mutex lock around
348   // all this stuff.
349   MutexLock l(&log_mutex);
350   for (int i = min_severity; i < NUM_SEVERITIES; i++) {
351     LogDestination* log = log_destination(i);
352     if (log != NULL) {
353       log->logger_->Flush();
354     }
355   }
356 }
357
358 inline void LogDestination::SetLogDestination(LogSeverity severity,
359                                               const char* base_filename) {
360   assert(severity >= 0 && severity < NUM_SEVERITIES);
361   // Prevent any subtle race conditions by wrapping a mutex lock around
362   // all this stuff.
363   MutexLock l(&log_mutex);
364   log_destination(severity)->fileobject_.SetBasename(base_filename);
365 }
366
367 inline void LogDestination::SetLogSymlink(LogSeverity severity,
368                                           const char* symlink_basename) {
369   CHECK_GE(severity, 0);
370   CHECK_LT(severity, NUM_SEVERITIES);
371   MutexLock l(&log_mutex);
372   log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
373 }
374
375 inline void LogDestination::AddLogSink(LogSink *destination) {
376   // Prevent any subtle race conditions by wrapping a mutex lock around
377   // all this stuff.
378   MutexLock l(&sink_mutex_);
379   if (!sinks_)  sinks_ = new vector<LogSink*>;
380   sinks_->push_back(destination);
381 }
382
383 inline void LogDestination::RemoveLogSink(LogSink *destination) {
384   // Prevent any subtle race conditions by wrapping a mutex lock around
385   // all this stuff.
386   MutexLock l(&sink_mutex_);
387   // This doesn't keep the sinks in order, but who cares?
388   if (sinks_) {
389     for (int i = sinks_->size() - 1; i >= 0; i--) {
390       if ((*sinks_)[i] == destination) {
391         (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
392         sinks_->pop_back();
393         break;
394       }
395     }
396   }
397 }
398
399 inline void LogDestination::SetLogFilenameExtension(const char* ext) {
400   // Prevent any subtle race conditions by wrapping a mutex lock around
401   // all this stuff.
402   MutexLock l(&log_mutex);
403   for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
404     log_destination(severity)->fileobject_.SetExtension(ext);
405   }
406 }
407
408 inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
409   assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
410   // Prevent any subtle race conditions by wrapping a mutex lock around
411   // all this stuff.
412   MutexLock l(&log_mutex);
413   FLAGS_stderrthreshold = min_severity;
414 }
415
416 inline void LogDestination::LogToStderr() {
417   // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
418   // SetLogDestination already do the locking!
419   SetStderrLogging(0);            // thus everything is "also" logged to stderr
420   for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
421     SetLogDestination(i, "");     // "" turns off logging to a logfile
422   }
423 }
424
425 inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
426                                             const char* addresses) {
427   assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
428   // Prevent any subtle race conditions by wrapping a mutex lock around
429   // all this stuff.
430   MutexLock l(&log_mutex);
431   LogDestination::email_logging_severity_ = min_severity;
432   LogDestination::addresses_ = addresses;
433 }
434
435 static void WriteToStderr(const char* message, size_t len) {
436   // Avoid using cerr from this module since we may get called during
437   // exit code, and cerr may be partially or fully destroyed by then.
438   write(STDERR_FILENO, message, len);
439 }
440
441 inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
442                                              const char* message, size_t len) {
443   if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
444     WriteToStderr(message, len);
445 #ifdef OS_WINDOWS
446     // On Windows, also output to the debugger
447     ::OutputDebugStringA(string(message,len).c_str());
448 #endif
449   }
450 }
451
452
453 inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
454                                             const char* message, size_t len) {
455   if (severity >= email_logging_severity_ ||
456       severity >= FLAGS_logemaillevel) {
457     string to(FLAGS_alsologtoemail);
458     if (!addresses_.empty()) {
459       if (!to.empty()) {
460         to += ",";
461       }
462       to += addresses_;
463     }
464     const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
465                          ProgramInvocationShortName());
466     string body(hostname());
467     body += "\n\n";
468     body.append(message, len);
469
470     // should NOT use SendEmail().  The caller of this function holds the
471     // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
472     // acquire the log_mutex object.  Use SendEmailInternal() and set
473     // use_logging to false.
474     SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
475   }
476 }
477
478
479 inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
480                                               time_t timestamp,
481                                               const char* message,
482                                               size_t len) {
483   const bool should_flush = severity > FLAGS_logbuflevel;
484   LogDestination* destination = log_destination(severity);
485   destination->logger_->Write(should_flush, timestamp, message, len);
486 }
487
488 inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
489                                              time_t timestamp,
490                                              const char* message,
491                                              size_t len) {
492
493   if ( FLAGS_logtostderr )            // global flag: never log to file
494     WriteToStderr(message, len);
495   else
496     for (int i = severity; i >= 0; --i)
497       LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
498
499 }
500
501 inline void LogDestination::LogToSinks(LogSeverity severity,
502                                        const char *full_filename,
503                                        const char *base_filename,
504                                        int line,
505                                        const struct ::tm* tm_time,
506                                        const char* message,
507                                        size_t message_len) {
508   ReaderMutexLock l(&sink_mutex_);
509   if (sinks_) {
510     for (int i = sinks_->size() - 1; i >= 0; i--) {
511       (*sinks_)[i]->send(severity, full_filename, base_filename,
512                          line, tm_time, message, message_len);
513     }
514   }
515 }
516
517 inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
518   ReaderMutexLock l(&sink_mutex_);
519   if (sinks_) {
520     for (int i = sinks_->size() - 1; i >= 0; i--) {
521       (*sinks_)[i]->WaitTillSent();
522     }
523   }
524   if (data->send_method_ == &LogMessage::SendToSinkAndLog &&
525       data->sink_ != NULL) {
526     data->sink_->WaitTillSent();
527   }
528 }
529
530 LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
531
532 inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
533   assert(severity >=0 && severity < NUM_SEVERITIES);
534   if (!log_destinations_[severity]) {
535     log_destinations_[severity] = new LogDestination(severity, NULL);
536   }
537   return log_destinations_[severity];
538 }
539
540 namespace {
541
542 LogFileObject::LogFileObject(LogSeverity severity,
543                              const char* base_filename)
544   : base_filename_selected_(base_filename != NULL),
545     base_filename_((base_filename != NULL) ? base_filename : ""),
546     symlink_basename_(ProgramInvocationShortName()),
547     filename_extension_(),
548     file_(NULL),
549     severity_(severity),
550     bytes_since_flush_(0),
551     file_length_(0),
552     rollover_attempt_(kRolloverAttemptFrequency-1),
553     next_flush_time_(0) {
554   assert(severity >= 0);
555   assert(severity < NUM_SEVERITIES);
556 }
557
558 LogFileObject::~LogFileObject() {
559   MutexLock l(&lock_);
560   if (file_ != NULL) {
561     fclose(file_);
562     file_ = NULL;
563   }
564 }
565
566 void LogFileObject::SetBasename(const char* basename) {
567   MutexLock l(&lock_);
568   base_filename_selected_ = true;
569   if (base_filename_ != basename) {
570     // Get rid of old log file since we are changing names
571     if (file_ != NULL) {
572       fclose(file_);
573       file_ = NULL;
574       rollover_attempt_ = kRolloverAttemptFrequency-1;
575     }
576     base_filename_ = basename;
577   }
578 }
579
580 void LogFileObject::SetExtension(const char* ext) {
581   MutexLock l(&lock_);
582   if (filename_extension_ != ext) {
583     // Get rid of old log file since we are changing names
584     if (file_ != NULL) {
585       fclose(file_);
586       file_ = NULL;
587       rollover_attempt_ = kRolloverAttemptFrequency-1;
588     }
589     filename_extension_ = ext;
590   }
591 }
592
593 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
594   MutexLock l(&lock_);
595   symlink_basename_ = symlink_basename;
596 }
597
598 void LogFileObject::Flush() {
599   MutexLock l(&lock_);
600   FlushUnlocked();
601 }
602
603 void LogFileObject::FlushUnlocked(){
604   if (file_ != NULL) {
605     fflush(file_);
606     bytes_since_flush_ = 0;
607   }
608   // Figure out when we are due for another flush.
609   const int64 next = (FLAGS_logbufsecs
610                       * static_cast<int64>(1000000));  // in usec
611   next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
612 }
613
614 bool LogFileObject::CreateLogfile(const char* time_pid_string) {
615   string string_filename = base_filename_+filename_extension_+
616                            time_pid_string;
617   const char* filename = string_filename.c_str();
618   int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
619   if (fd == -1) return false;
620 #ifdef HAVE_FCNTL
621   // Mark the file close-on-exec. We don't really care if this fails
622   fcntl(fd, F_SETFD, FD_CLOEXEC);
623 #endif
624
625   file_ = fdopen(fd, "a");  // Make a FILE*.
626   if (file_ == NULL) {  // Man, we're screwed!
627     close(fd);
628     unlink(filename);  // Erase the half-baked evidence: an unusable log file
629     return false;
630   }
631
632   // We try to create a symlink called <program_name>.<severity>,
633   // which is easier to use.  (Every time we create a new logfile,
634   // we destroy the old symlink and create a new one, so it always
635   // points to the latest logfile.)  If it fails, we're sad but it's
636   // no error.
637   if (!symlink_basename_.empty()) {
638     // take directory from filename
639     const char* slash = strrchr(filename, PATH_SEPARATOR);
640     const string linkname =
641       symlink_basename_ + '.' + LogSeverityNames[severity_];
642     string linkpath;
643     if ( slash ) linkpath = string(filename, slash-filename+1);  // get dirname
644     linkpath += linkname;
645     unlink(linkpath.c_str());                    // delete old one if it exists
646
647     // We must have unistd.h.
648 #ifdef HAVE_UNISTD_H
649     // Make the symlink be relative (in the same dir) so that if the
650     // entire log directory gets relocated the link is still valid.
651     const char *linkdest = slash ? (slash + 1) : filename;
652     symlink(linkdest, linkpath.c_str());         // silently ignore failures
653
654     // Make an additional link to the log file in a place specified by
655     // FLAGS_log_link, if indicated
656     if (!FLAGS_log_link.empty()) {
657       linkpath = FLAGS_log_link + "/" + linkname;
658       unlink(linkpath.c_str());                  // delete old one if it exists
659       symlink(filename, linkpath.c_str());       // silently ignore failures
660     }
661 #endif
662   }
663
664   return true;  // Everything worked
665 }
666
667 void LogFileObject::Write(bool force_flush,
668                           time_t timestamp,
669                           const char* message,
670                           int message_len) {
671   MutexLock l(&lock_);
672
673   // We don't log if the base_name_ is "" (which means "don't write")
674   if (base_filename_selected_ && base_filename_.empty()) {
675     return;
676   }
677
678   if (static_cast<int>(file_length_ >> 20) >= FLAGS_max_log_size) {
679     fclose(file_);
680     file_ = NULL;
681     file_length_ = bytes_since_flush_ = 0;
682     rollover_attempt_ = kRolloverAttemptFrequency-1;
683   }
684
685   // If there's no destination file, make one before outputting
686   if (file_ == NULL) {
687     // Try to rollover the log file every 32 log messages.  The only time
688     // this could matter would be when we have trouble creating the log
689     // file.  If that happens, we'll lose lots of log messages, of course!
690     if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
691     rollover_attempt_ = 0;
692
693     struct ::tm tm_time;
694     localtime_r(&timestamp, &tm_time);
695
696     // The logfile's filename will have the date/time & pid in it
697     char time_pid_string[256];  // More than enough chars for time, pid, \0
698     ostrstream time_pid_stream(time_pid_string, sizeof(time_pid_string));
699     time_pid_stream.fill('0');
700     time_pid_stream << 1900+tm_time.tm_year
701                     << setw(2) << 1+tm_time.tm_mon
702                     << setw(2) << tm_time.tm_mday
703                     << '-'
704                     << setw(2) << tm_time.tm_hour
705                     << setw(2) << tm_time.tm_min
706                     << setw(2) << tm_time.tm_sec
707                     << '.'
708                     << GetMainThreadPid()
709                     << '\0';
710
711     if (base_filename_selected_) {
712       if (!CreateLogfile(time_pid_string)) {
713         perror("Could not create log file");
714         fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", time_pid_string);
715         return;
716       }
717     } else {
718       // If no base filename for logs of this severity has been set, use a
719       // default base filename of
720       // "<program name>.<hostname>.<user name>.log.<severity level>.".  So
721       // logfiles will have names like
722       // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
723       // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
724       // and 4354 is the pid of the logging process.  The date & time reflect
725       // when the file was created for output.
726       //
727       // Where does the file get put?  Successively try the directories
728       // "/tmp", and "."
729       string stripped_filename(ProgramInvocationShortName());  // in cmdlineflag
730       string hostname;
731       GetHostName(&hostname);
732
733       string uidname = MyUserName();
734       // We should not call CHECK() here because this function can be
735       // called after holding on to log_mutex. We don't want to
736       // attempt to hold on to the same mutex, and get into a
737       // deadlock. Simply use a name like invalid-user.
738       if (uidname.empty()) uidname = "invalid-user";
739
740       stripped_filename = stripped_filename+'.'+hostname+'.'
741                           +uidname+".log."
742                           +LogSeverityNames[severity_]+'.';
743       // We're going to (potentially) try to put logs in several different dirs
744       const vector<string> & log_dirs = GetLoggingDirectories();
745
746       // Go through the list of dirs, and try to create the log file in each
747       // until we succeed or run out of options
748       bool success = false;
749       for (vector<string>::const_iterator dir = log_dirs.begin();
750            dir != log_dirs.end();
751            ++dir) {
752         base_filename_ = *dir + "/" + stripped_filename;
753         if ( CreateLogfile(time_pid_string) ) {
754           success = true;
755           break;
756         }
757       }
758       // If we never succeeded, we have to give up
759       if ( success == false ) {
760         perror("Could not create logging file");
761         fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", time_pid_string);
762         return;
763       }
764     }
765
766     // Write a header message into the log file
767     char file_header_string[512];  // Enough chars for time and binary info
768     ostrstream file_header_stream(file_header_string,
769                                   sizeof(file_header_string));
770     file_header_stream.fill('0');
771     file_header_stream << "Log file created at: "
772                        << 1900+tm_time.tm_year << '/'
773                        << setw(2) << 1+tm_time.tm_mon << '/'
774                        << setw(2) << tm_time.tm_mday
775                        << ' '
776                        << setw(2) << tm_time.tm_hour << ':'
777                        << setw(2) << tm_time.tm_min << ':'
778                        << setw(2) << tm_time.tm_sec << '\n'
779                        << "Running on machine: "
780                        << LogDestination::hostname() << '\n'
781                        << '\0';
782     int header_len = strlen(file_header_string);
783     fwrite(file_header_string, 1, header_len, file_);
784     file_length_ += header_len;
785     bytes_since_flush_ += header_len;
786   }
787
788   // Write to LOG file
789   if ( !stop_writing ) {
790     // fwrite() doesn't return an error when the disk is full, for
791     // messages that are less than 4096 bytes. When the disk is full,
792     // it returns the message length for messages that are less than
793     // 4096 bytes. fwrite() returns 4096 for message lengths that are
794     // greater than 4096, thereby indicating an error.
795     errno = 0;
796     fwrite(message, 1, message_len, file_);
797     if ( FLAGS_stop_logging_if_full_disk &&
798          errno == ENOSPC ) {  // disk full, stop writing to disk
799       stop_writing = true;  // until the disk is
800       return;
801     } else {
802       file_length_ += message_len;
803       bytes_since_flush_ += message_len;
804     }
805   } else {
806     if ( CycleClock_Now() >= next_flush_time_ )
807       stop_writing = false;  // check to see if disk has free space.
808     return;  // no need to flush
809   }
810
811   // See important msgs *now*.  Also, flush logs at least every 10^6 chars,
812   // or every "FLAGS_logbufsecs" seconds.
813   if ( force_flush ||
814        (bytes_since_flush_ >= 1000000) ||
815        (CycleClock_Now() >= next_flush_time_) ) {
816     FlushUnlocked();
817   }
818 }
819
820 }  // namespace
821
822 //
823 // LogMessage's constructor starts each message with a string like:
824 // I1018 160715 logging.cc:1153]
825 // (1st letter of severity level, GMT month, date, & time;
826 // thread id (if not 0x400); basename of file and line of the logging command)
827 // We ignore thread id 0x400 because it seems to be the default for single-
828 // threaded programs.
829
830 // An arbitrary limit on the length of a single log message.  This
831 // is so that streaming can be done more efficiently.
832 const size_t LogMessage::kMaxLogMessageLen = 30000;
833
834 // Need to reserve some space for FATAL messages because
835 // we usually do LOG(FATAL) when we ran out of heap memory.
836 // However, since LogMessage() also calls new[], in this case,
837 // it will recusively call LOG(FATAL), which then call new[] ... etc.
838 // Eventually, the program will run out of stack memory and no message
839 // will get logged.   Note that we will not be protecting this buffer
840 // with a lock because the chances are very small that there will
841 // be a contention during LOG(FATAL) which can only happen at most
842 // once per program.
843 static char fatal_message_buffer[LogMessage::kMaxLogMessageLen+1];
844
845 // Similarly we reserve space for a LogMessageData struct to be used
846 // for FATAL messages.
847 LogMessage::LogMessageData LogMessage::fatal_message_data_(0, FATAL, 0);
848
849 LogMessage::LogMessageData::LogMessageData(int preserved_errno,
850                                            LogSeverity severity,
851                                            int ctr) :
852     // ORDER DEPENDENCY: buf_ comes before message_text_ comes before stream_
853     preserved_errno_(preserved_errno),
854     // Use static buffer for LOG(FATAL)
855     buf_((severity != FATAL) ? new char[kMaxLogMessageLen+1] : NULL),
856     message_text_((severity != FATAL) ? buf_ : fatal_message_buffer),
857     stream_(message_text_, kMaxLogMessageLen, ctr),
858     severity_(severity) {
859 }
860
861 LogMessage::LogMessageData::~LogMessageData() {
862   delete[] buf_;
863 }
864
865 LogMessage::LogMessageData* LogMessage::GetMessageData(int preserved_errno,
866                                                        LogSeverity severity,
867                                                        int ctr) {
868   if (severity != FATAL) {
869     return allocated_;
870   } else {
871     fatal_message_data_.preserved_errno_ = preserved_errno;
872     fatal_message_data_.stream_.set_ctr(ctr);
873     return &fatal_message_data_;
874   }
875 }
876
877 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
878                        int ctr, void (LogMessage::*send_method)()) :
879     allocated_((severity != FATAL) ?
880                new LogMessageData(errno, severity, ctr) : NULL),
881     data_(GetMessageData(errno, severity, ctr)) {
882   Init(file, line, severity, send_method);
883 }
884
885 LogMessage::LogMessage(const char* file, int line, const CheckOpString& result)
886     : allocated_(NULL),
887       data_(GetMessageData(errno, FATAL, 0)) {
888   Init(file, line, FATAL, &LogMessage::SendToLog);
889   stream() << "Check failed: " << (*result.str_) << " ";
890 }
891
892 LogMessage::LogMessage(const char* file, int line) :
893     allocated_(new LogMessageData(errno, INFO, 0)),
894     data_(GetMessageData(errno, INFO, 0)) {
895   Init(file, line, INFO, &LogMessage::SendToLog);
896 }
897
898 LogMessage::LogMessage(const char* file, int line, LogSeverity severity) :
899     allocated_((severity != FATAL) ?
900                new LogMessageData(errno, severity, 0) : NULL),
901     data_(GetMessageData(errno, severity, 0)) {
902   Init(file, line, severity, &LogMessage::SendToLog);
903 }
904
905 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
906                        LogSink* sink) :
907     allocated_((severity != FATAL) ?
908                new LogMessageData(errno, severity, 0) : NULL),
909     data_(GetMessageData(errno, severity, 0)) {
910   Init(file, line, severity, &LogMessage::SendToSinkAndLog);
911   data_->sink_ = sink;  // override Init()'s setting to NULL
912 }
913
914 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
915                        vector<string> *outvec) :
916     allocated_((severity != FATAL) ?
917                new LogMessageData(errno, severity, 0) : NULL),
918     data_(GetMessageData(errno, severity, 0)) {
919   Init(file, line, severity, &LogMessage::SaveOrSendToLog);
920   data_->outvec_ = outvec; // override Init()'s setting to NULL
921 }
922
923 void LogMessage::Init(const char* file, int line, LogSeverity severity,
924                       void (LogMessage::*send_method)()) {
925   data_->line_ = line;
926   data_->send_method_ = send_method;
927
928   data_->outvec_ = NULL;
929   data_->sink_ = NULL;
930   data_->timestamp_ = time(NULL);
931   localtime_r(&data_->timestamp_, &data_->tm_time_);
932   RawLog__SetLastTime(data_->tm_time_);
933   data_->basename_ = const_basename(file);
934   data_->fullname_ = file;
935   data_->stream_.fill('0');
936
937   // In some cases, we use logging like a print mechanism and
938   // the prefixes get in the way
939   if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
940     if ( is_default_thread() ) {
941       stream() << LogSeverityNames[severity][0]
942                << setw(2) << 1+data_->tm_time_.tm_mon
943                << setw(2) << data_->tm_time_.tm_mday
944                << ' '
945                << setw(2) << data_->tm_time_.tm_hour
946                << setw(2) << data_->tm_time_.tm_min
947                << setw(2) << data_->tm_time_.tm_sec
948                << ' ' << data_->basename_ << ':' << data_->line_ << "] ";
949     } else {
950       stream() << LogSeverityNames[severity][0]
951                << setw(2) << 1+data_->tm_time_.tm_mon
952                << setw(2) << data_->tm_time_.tm_mday
953                << ' '
954                << setw(2) << data_->tm_time_.tm_hour
955                << setw(2) << data_->tm_time_.tm_min
956                << setw(2) << data_->tm_time_.tm_sec
957                << ' ' << setw(8) << std::hex << pthread_self() << std::dec
958                << ' ' << data_->basename_ << ':' << data_->line_ << "] ";
959     }
960   }
961
962   data_->num_prefix_chars_ = data_->stream_.pcount();
963   data_->has_been_flushed_ = false;
964 }
965
966 LogMessage::~LogMessage() {
967   Flush();
968   delete allocated_;
969 }
970
971 // Flush buffered message, called by the destructor, or any other function
972 // that needs to synchronize the log.
973 void LogMessage::Flush() {
974   if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
975     return;
976
977   data_->num_chars_to_log_ = data_->stream_.pcount();
978   data_->num_chars_to_syslog_ =
979     data_->num_chars_to_log_ - data_->num_prefix_chars_;
980
981   // Do we need to add a \n to the end of this message?
982   bool append_newline =
983     (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
984   char original_final_char = '\0';
985
986   // If we do need to add a \n, we'll do it by violating the memory of the
987   // ostrstream buffer.  This is quick, and we'll make sure to undo our
988   // modification before anything else is done with the ostrstream.  It
989   // would be preferable not to do things this way, but it seems to be
990   // the best way to deal with this.
991   if (append_newline) {
992     original_final_char = data_->message_text_[data_->num_chars_to_log_];
993     data_->message_text_[data_->num_chars_to_log_++] = '\n';
994   }
995
996   // Prevent any subtle race conditions by wrapping a mutex lock around
997   // the actual logging action per se.
998   {
999     MutexLock l(&log_mutex);
1000     (this->*(data_->send_method_))();
1001     ++num_messages_[static_cast<int>(data_->severity_)];
1002   }
1003   LogDestination::WaitForSinks(data_);
1004
1005   if (append_newline) {
1006     // Fix the ostrstream back how it was before we screwed with it.
1007     // It's 99.44% certain that we don't need to worry about doing this.
1008     data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1009   }
1010
1011   // If errno was already set before we enter the logging call, we'll
1012   // set it back to that value when we return from the logging call.
1013   // It happens often that we log an error message after a syscall
1014   // failure, which can potentially set the errno to some other
1015   // values.  We would like to preserve the original errno.
1016   if (data_->preserved_errno_ != 0) {
1017     errno = data_->preserved_errno_;
1018   }
1019
1020   // Note that this message is now safely logged.  If we're asked to flush
1021   // again, as a result of destruction, say, we'll do nothing on future calls.
1022   data_->has_been_flushed_ = true;
1023 }
1024
1025 // Copy of FATAL log message so that we can print it out again after
1026 // all the stack traces.
1027 // We cannot simply use fatal_message_buffer, because two or more FATAL log
1028 // messages may happen in a row. This is a real possibility given that
1029 // FATAL log messages are often associated with corrupted process state.
1030 // In this case, we still want to reprint the first FATAL log message, so
1031 // we need to save away the first message in a separate buffer.
1032 static time_t fatal_time;
1033 static char fatal_message[256];
1034
1035 void ReprintFatalMessage() {
1036   if (fatal_message[0]) {
1037     const int n = strlen(fatal_message);
1038     if (!FLAGS_logtostderr) {
1039       // Also write to stderr
1040       WriteToStderr(fatal_message, n);
1041     }
1042     LogDestination::LogToAllLogfiles(ERROR, fatal_time, fatal_message, n);
1043   }
1044 }
1045
1046 // L >= log_mutex (callers must hold the log_mutex).
1047 void LogMessage::SendToLog() {
1048   static bool already_warned_before_initgoogle = false;
1049
1050   log_mutex.AssertHeld();
1051
1052   RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1053              data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1054
1055   // Messages of a given severity get logged to lower severity logs, too
1056
1057   if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1058     const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1059                      "written to STDERR\n";
1060     WriteToStderr(w, strlen(w));
1061     already_warned_before_initgoogle = true;
1062   }
1063
1064   // global flag: never log to file if set.  Also -- don't log to a
1065   // file if we haven't parsed the command line flags to get the
1066   // program name.
1067   if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1068     WriteToStderr(data_->message_text_, data_->num_chars_to_log_);
1069
1070     // this could be protected by a flag if necessary.
1071     LogDestination::LogToSinks(data_->severity_,
1072                                data_->fullname_, data_->basename_,
1073                                data_->line_, &data_->tm_time_,
1074                                data_->message_text_ + data_->num_prefix_chars_,
1075                                (data_->num_chars_to_log_ -
1076                                 data_->num_prefix_chars_ - 1));
1077   } else {
1078
1079     // log this message to all log files of severity <= severity_
1080     LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1081                                      data_->message_text_,
1082                                      data_->num_chars_to_log_);
1083
1084     LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1085                                      data_->num_chars_to_log_);
1086     LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1087                                     data_->num_chars_to_log_);
1088     LogDestination::LogToSinks(data_->severity_,
1089                                data_->fullname_, data_->basename_,
1090                                data_->line_, &data_->tm_time_,
1091                                data_->message_text_ + data_->num_prefix_chars_,
1092                                (data_->num_chars_to_log_
1093                                 - data_->num_prefix_chars_ - 1));
1094     // NOTE: -1 removes trailing \n
1095   }
1096
1097   // If we log a FATAL message, flush all the log destinations, then toss
1098   // a signal for others to catch. We leave the logs in a state that
1099   // someone else can use them (as long as they flush afterwards)
1100   if (data_->severity_ == FATAL) {
1101     // save away the fatal message so we can print it again later
1102     const int copy = min<int>(data_->num_chars_to_log_,
1103                               sizeof(fatal_message)-1);
1104     memcpy(fatal_message, data_->message_text_, copy);
1105     fatal_message[copy] = '\0';
1106     fatal_time = data_->timestamp_;
1107
1108     if (!FLAGS_logtostderr) {
1109       for (int i = 0; i < NUM_SEVERITIES; ++i) {
1110         if ( LogDestination::log_destinations_[i] )
1111           LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1112       }
1113     }
1114     
1115     // release the lock that our caller (directly or indirectly)
1116     // LogMessage::~LogMessage() grabbed so that signal handlers
1117     // can use the logging facility. Alternately, we could add
1118     // an entire unsafe logging interface to bypass locking
1119     // for signal handlers but this seems simpler.
1120     log_mutex.Unlock();
1121     LogDestination::WaitForSinks(data_);
1122
1123     Fail();
1124   }
1125 }
1126
1127 static void logging_fail() {
1128 #if defined(_DEBUG) && defined(_MSC_VER)
1129   // When debugging on windows, avoid the obnoxious dialog and make
1130   // it possible to continue past a LOG(FATAL) in the debugger
1131   _asm int 3
1132 #else
1133   abort();
1134 #endif
1135 }
1136
1137 #ifdef HAVE___ATTRIBUTE__
1138 GOOGLE_GLOG_DLL_DECL
1139 void (*g_logging_fail_func)() __attribute__((noreturn)) = &logging_fail;
1140 #else
1141 GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)() = &logging_fail;
1142 #endif
1143
1144 void InstallFailureFunction(void (*fail_func)()) {
1145   g_logging_fail_func = fail_func;
1146 }
1147
1148 void LogMessage::Fail() {
1149   g_logging_fail_func();
1150 }
1151
1152 // L >= log_mutex (callers must hold the log_mutex).
1153 void LogMessage::SendToSinkAndLog() {
1154   if (data_->sink_ != NULL) {
1155     RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1156                data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1157     data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1158                        data_->line_, &data_->tm_time_,
1159                        data_->message_text_ + data_->num_prefix_chars_,
1160                        (data_->num_chars_to_log_ -
1161                         data_->num_prefix_chars_ - 1));
1162   }
1163   SendToLog();
1164 }
1165
1166 // L >= log_mutex (callers must hold the log_mutex).
1167 void LogMessage::SaveOrSendToLog() {
1168   if (data_->outvec_ != NULL) {
1169     RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1170                data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1171     // Omit prefix of message and trailing newline when recording in outvec_.
1172     const char *start = data_->message_text_ + data_->num_prefix_chars_;
1173     int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1174     data_->outvec_->push_back(string(start, len));
1175   } else {
1176     SendToLog();
1177   }
1178 }
1179
1180 // L >= log_mutex (callers must hold the log_mutex).
1181 void LogMessage::SendToSyslogAndLog() {
1182 #ifdef HAVE_SYSLOG_H
1183   // Before any calls to syslog(), make a single call to openlog()
1184   static bool openlog_already_called = false;
1185   if (!openlog_already_called) {
1186     openlog(ProgramInvocationShortName(), LOG_CONS | LOG_NDELAY | LOG_PID,
1187             LOG_USER);
1188     openlog_already_called = true;
1189   }
1190
1191   // This array maps Google severity levels to syslog levels
1192   const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1193   syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1194          int(data_->num_chars_to_syslog_),
1195          data_->message_text_ + data_->num_prefix_chars_);
1196   SendToLog();
1197 #else
1198   LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1199 #endif
1200 }
1201
1202 base::Logger* base::GetLogger(LogSeverity severity) {
1203   MutexLock l(&log_mutex);
1204   return LogDestination::log_destination(severity)->logger_;
1205 }
1206
1207 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1208   MutexLock l(&log_mutex);
1209   LogDestination::log_destination(severity)->logger_ = logger;
1210 }
1211
1212 // L < log_mutex.  Acquires and releases mutex_.
1213 int64 LogMessage::num_messages(int severity) {
1214   MutexLock l(&log_mutex);
1215   return num_messages_[severity];
1216 }
1217
1218 // Output the COUNTER value. This is only valid if ostream is a
1219 // LogStream.
1220 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1221   LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1222   CHECK(log == log->self());
1223   os << log->ctr();
1224   return os;
1225 }
1226
1227 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1228                                  LogSeverity severity, int ctr,
1229                                  void (LogMessage::*send_method)())
1230     : LogMessage(file, line, severity, ctr, send_method) {
1231 }
1232
1233 ErrnoLogMessage::~ErrnoLogMessage() {
1234   // Don't access errno directly because it may have been altered
1235   // while streaming the message.
1236   char buf[100];
1237   posix_strerror_r(preserved_errno(), buf, sizeof(buf));
1238   stream() << ": " << buf << " [" << preserved_errno() << "]";
1239 }
1240
1241 void FlushLogFiles(LogSeverity min_severity) {
1242   LogDestination::FlushLogFiles(min_severity);
1243 }
1244
1245 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1246   LogDestination::FlushLogFilesUnsafe(min_severity);
1247 }
1248
1249 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1250   LogDestination::SetLogDestination(severity, base_filename);
1251 }
1252
1253 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1254   LogDestination::SetLogSymlink(severity, symlink_basename);
1255 }
1256
1257 LogSink::~LogSink() {
1258 }
1259
1260 void LogSink::WaitTillSent() {
1261   // noop default
1262 }
1263
1264 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1265                          const struct ::tm* tm_time,
1266                          const char* message, size_t message_len) {
1267   ostringstream stream(string(message, message_len));
1268   stream.fill('0');
1269
1270   if ( is_default_thread() ) {
1271     stream << LogSeverityNames[severity][0]
1272            << setw(2) << 1+tm_time->tm_mon
1273            << setw(2) << tm_time->tm_mday
1274            << ' '
1275            << setw(2) << tm_time->tm_hour
1276            << setw(2) << tm_time->tm_min
1277            << setw(2) << tm_time->tm_sec
1278            << ' ' << file << ':' << line << "] ";
1279   } else {
1280     stream << LogSeverityNames[severity][0]
1281            << setw(2) << 1+tm_time->tm_mon
1282            << setw(2) << tm_time->tm_mday
1283            << ' '
1284            << setw(2) << tm_time->tm_hour
1285            << setw(2) << tm_time->tm_min
1286            << setw(2) << tm_time->tm_sec
1287            << ' ' << setw(8) << std::hex << pthread_self() << std::dec
1288            << ' ' << file << ':' << line << "] ";
1289   }
1290
1291   stream << string(message, message_len);
1292   return stream.str();
1293 }
1294
1295 void AddLogSink(LogSink *destination) {
1296   LogDestination::AddLogSink(destination);
1297 }
1298
1299 void RemoveLogSink(LogSink *destination) {
1300   LogDestination::RemoveLogSink(destination);
1301 }
1302
1303 void SetLogFilenameExtension(const char* ext) {
1304   LogDestination::SetLogFilenameExtension(ext);
1305 }
1306
1307 void SetStderrLogging(LogSeverity min_severity) {
1308   LogDestination::SetStderrLogging(min_severity);
1309 }
1310
1311 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1312   LogDestination::SetEmailLogging(min_severity, addresses);
1313 }
1314
1315 void LogToStderr() {
1316   LogDestination::LogToStderr();
1317 }
1318
1319 // use_logging controls whether the logging functions LOG/VLOG are used
1320 // to log errors.  It should be set to false when the caller holds the
1321 // log_mutex.
1322 static bool SendEmailInternal(const char*dest, const char *subject,
1323                               const char*body, bool use_logging) {
1324   if (dest && *dest) {
1325     if ( use_logging ) {
1326       VLOG(1) << "Trying to send TITLE:" << subject
1327               << " BODY:" << body << " to " << dest;
1328     } else {
1329       fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1330               subject, body, dest);
1331     }
1332
1333     string cmd(FLAGS_logmailer);
1334     cmd = cmd + " -s\"" + string(subject) + "\" " + string(dest);
1335     FILE* pipe = popen(cmd.c_str(), "w");
1336     if (pipe != NULL) {
1337       // Add the body if we have one
1338       if (body)
1339         fwrite(body, sizeof(char), strlen(body), pipe);
1340       bool ok = pclose(pipe) != -1;
1341       if ( !ok ) {
1342         if ( use_logging ) {
1343           char buf[100];
1344           posix_strerror_r(errno, buf, sizeof(buf));
1345           LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf;
1346         } else {
1347           char buf[100];
1348           posix_strerror_r(errno, buf, sizeof(buf));
1349           fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf);
1350         }
1351       }
1352       return ok;
1353     } else {
1354       if ( use_logging ) {
1355         LOG(ERROR) << "Unable to send mail to " << dest;
1356       } else {
1357         fprintf(stderr, "Unable to send mail to %s\n", dest);
1358       }
1359     }
1360   }
1361   return false;
1362 }
1363
1364 bool SendEmail(const char*dest, const char *subject, const char*body){
1365   return SendEmailInternal(dest, subject, body, true);
1366 }
1367
1368 static void GetTempDirectories(vector<string>* list) {
1369   list->clear();
1370 #ifdef OS_WINDOWS
1371   // On windows we'll try to find a directory in this order:
1372   //   C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1373   //   C:/TMP/
1374   //   C:/TEMP/
1375   //   C:/WINDOWS/ or C:/WINNT/
1376   //   .
1377   char tmp[MAX_PATH];
1378   if (GetTempPathA(MAX_PATH, tmp))
1379     list->push_back(tmp);
1380   list->push_back("C:\\tmp\\");
1381   list->push_back("C:\\temp\\");
1382 #else
1383   // Directories, in order of preference. If we find a dir that
1384   // exists, we stop adding other less-preferred dirs
1385   const char * candidates[] = {
1386     // Non-null only during unittest/regtest
1387     getenv("TEST_TMPDIR"),
1388
1389     // Explicitly-supplied temp dirs
1390     getenv("TMPDIR"), getenv("TMP"),
1391
1392     // If all else fails
1393     "/tmp",
1394   };
1395
1396   for (int i = 0; i < ARRAYSIZE(candidates); i++) {
1397     const char *d = candidates[i];
1398     if (!d) continue;  // Empty env var
1399
1400     // Make sure we don't surprise anyone who's expecting a '/'
1401     string dstr = d;
1402     if (dstr[dstr.size() - 1] != '/') {
1403       dstr += "/";
1404     }
1405     list->push_back(dstr);
1406
1407     struct stat statbuf;
1408     if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1409       // We found a dir that exists - we're done.
1410       return;
1411     }
1412   }
1413
1414 #endif
1415 }
1416
1417 static vector<string>* logging_directories_list;
1418
1419 const vector<string>& GetLoggingDirectories() {
1420   // Not strictly thread-safe but we're called early in InitGoogle().
1421   if (logging_directories_list == NULL) {
1422     logging_directories_list = new vector<string>;
1423
1424     if ( !FLAGS_log_dir.empty() ) {
1425       // A dir was specified, we should use it
1426       logging_directories_list->push_back(FLAGS_log_dir.c_str());
1427     } else {
1428       GetTempDirectories(logging_directories_list);
1429 #ifdef OS_WINDOWS
1430       char tmp[MAX_PATH];
1431       if (GetWindowsDirectoryA(tmp, MAX_PATH))
1432         logging_directories_list->push_back(tmp);
1433       logging_directories_list->push_back(".\\");
1434 #else
1435       logging_directories_list->push_back("./");
1436 #endif
1437     }
1438   }
1439   return *logging_directories_list;
1440 }
1441
1442 void TestOnly_ClearLoggingDirectoriesList() {
1443   fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1444           "called from test code.\n");
1445   delete logging_directories_list;
1446   logging_directories_list = NULL;
1447 }
1448
1449 void GetExistingTempDirectories(vector<string>* list) {
1450   GetTempDirectories(list);
1451   vector<string>::iterator i_dir = list->begin();
1452   while( i_dir != list->end() ) {
1453     // zero arg to access means test for existence; no constant
1454     // defined on windows
1455     if ( access(i_dir->c_str(), 0) ) {
1456       i_dir = list->erase(i_dir);
1457     } else {
1458       ++i_dir;
1459     }
1460   }
1461 }
1462
1463 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1464 #ifdef HAVE_UNISTD_H
1465   struct stat statbuf;
1466   const int kCopyBlockSize = 8 << 10;
1467   char copybuf[kCopyBlockSize];
1468   int64 read_offset, write_offset;
1469   // Don't follow symlinks unless they're our own fd symlinks in /proc
1470   int flags = O_RDWR;
1471   const char *procfd_prefix = "/proc/self/fd/";
1472   if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1473
1474   int fd = open(path, flags);
1475   if (fd == -1) {
1476     if (errno == EFBIG) {
1477       // The log file in question has got too big for us to open. The
1478       // real fix for this would be to compile logging.cc (or probably
1479       // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1480       // rather scary.
1481       // Instead just truncate the file to something we can manage
1482       if (truncate(path, 0) == -1) {
1483         PLOG(ERROR) << "Unable to truncate " << path;
1484       } else {
1485         LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1486       }
1487     } else {
1488       PLOG(ERROR) << "Unable to open " << path;
1489     }
1490     return;
1491   }
1492   
1493   if (fstat(fd, &statbuf) == -1) {
1494     PLOG(ERROR) << "Unable to fstat()"; 
1495     goto out_close_fd; 
1496   }
1497
1498   // See if the path refers to a regular file bigger than the
1499   // specified limit
1500   if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1501   if (statbuf.st_size <= limit)  goto out_close_fd;
1502   if (statbuf.st_size <= keep) goto out_close_fd;
1503
1504   // This log file is too large - we need to truncate it
1505   LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1506   
1507   // Copy the last "keep" bytes of the file to the beginning of the file
1508   read_offset = statbuf.st_size - keep; 
1509   write_offset = 0;
1510   int bytesin, bytesout;
1511   while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1512     bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1513     if (bytesout == -1) {
1514       PLOG(ERROR) << "Unable to write to " << path;
1515       break;
1516     } else if (bytesout != bytesin) {
1517       LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1518     }
1519     read_offset += bytesin;
1520     write_offset += bytesout;
1521   }
1522   if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1523   
1524   // Truncate the remainder of the file. If someone else writes to the
1525   // end of the file after our last read() above, we lose their latest
1526   // data. Too bad ...
1527   if (ftruncate(fd, write_offset) == -1) {
1528     PLOG(ERROR) << "Unable to truncate " << path;
1529   }
1530
1531  out_close_fd:
1532   close(fd);
1533 #else
1534   LOG(ERROR) << "No log truncation support.";
1535 #endif
1536 }
1537
1538 void TruncateStdoutStderr() {
1539 #ifdef HAVE_UNISTD_H
1540   int64 limit = FLAGS_max_log_size << 20;
1541   int64 keep = 1 << 20;
1542   TruncateLogFile("/proc/self/fd/1", limit, keep);
1543   TruncateLogFile("/proc/self/fd/2", limit, keep);
1544 #else
1545   LOG(ERROR) << "No log truncation support.";
1546 #endif
1547 }
1548
1549
1550 // Helper functions for string comparisons.
1551 #define DEFINE_CHECK_STROP_IMPL(name, func, expected)                   \
1552   string* Check##func##expected##Impl(const char* s1, const char* s2,   \
1553                                       const char* names) {              \
1554     bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2));               \
1555     if (equal == expected) return NULL;                                 \
1556     else {                                                              \
1557       strstream ss;                                                     \
1558       if (!s1) s1 = "";                                                 \
1559       if (!s2) s2 = "";                                                 \
1560       ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1561       return new string(ss.str(), ss.pcount());                         \
1562     }                                                                   \
1563   }
1564 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1565 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1566 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1567 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1568 #undef DEFINE_CHECK_STROP_IMPL
1569
1570 int posix_strerror_r(int err, char *buf, size_t len) {
1571   // Sanity check input parameters
1572   if (buf == NULL || len <= 0) {
1573     errno = EINVAL;
1574     return -1;
1575   }
1576
1577   // Reset buf and errno, and try calling whatever version of strerror_r()
1578   // is implemented by glibc
1579   buf[0] = '\000';
1580   int old_errno = errno;
1581   errno = 0;
1582   char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1583
1584   // Both versions set errno on failure
1585   if (errno) {
1586     // Should already be there, but better safe than sorry
1587     buf[0]     = '\000';
1588     return -1;
1589   }
1590   errno = old_errno;
1591
1592   // POSIX is vague about whether the string will be terminated, although
1593   // is indirectly implies that typically ERANGE will be returned, instead
1594   // of truncating the string. This is different from the GNU implementation.
1595   // We play it safe by always terminating the string explicitly.
1596   buf[len-1] = '\000';
1597
1598   // If the function succeeded, we can use its exit code to determine the
1599   // semantics implemented by glibc
1600   if (!rc) {
1601     return 0;
1602   } else {
1603     // GNU semantics detected
1604     if (rc == buf) {
1605       return 0;
1606     } else {
1607       buf[0] = '\000';
1608 #if defined(OS_MACOSX) || defined(OS_FREEBSD)
1609       if (reinterpret_cast<int>(rc) < sys_nerr) {
1610         // This means an error on MacOSX or FreeBSD.
1611         return -1;
1612       }
1613 #endif
1614       strncat(buf, rc, len-1);
1615       return 0;
1616     }
1617   }
1618 }
1619
1620 LogMessageFatal::LogMessageFatal(const char* file, int line) :
1621     LogMessage(file, line, FATAL) {}
1622
1623 LogMessageFatal::LogMessageFatal(const char* file, int line,
1624                                  const CheckOpString& result) :
1625     LogMessage(file, line, result) {}
1626
1627 LogMessageFatal::~LogMessageFatal() {
1628     Flush();
1629     LogMessage::Fail();
1630 }
1631
1632 _END_GOOGLE_NAMESPACE_