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