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