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