/thirdparty/breakpad/third_party/glog/src/logging.cc

http://github.com/tomahawk-player/tomahawk · C++ · 1808 lines · 1288 code · 226 blank · 294 comment · 225 complexity · cf7b2eac37b87263cb124fcaed0d9042 MD5 · raw file

Large files are truncated click here to view the full file

  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. #define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite()
  30. #include "utilities.h"
  31. #include <assert.h>
  32. #include <iomanip>
  33. #include <string>
  34. #ifdef HAVE_UNISTD_H
  35. # include <unistd.h> // For _exit.
  36. #endif
  37. #include <climits>
  38. #include <sys/types.h>
  39. #include <sys/stat.h>
  40. #ifdef HAVE_SYS_UTSNAME_H
  41. # include <sys/utsname.h> // For uname.
  42. #endif
  43. #include <fcntl.h>
  44. #include <cstdio>
  45. #include <iostream>
  46. #include <stdarg.h>
  47. #include <stdlib.h>
  48. #ifdef HAVE_PWD_H
  49. # include <pwd.h>
  50. #endif
  51. #ifdef HAVE_SYSLOG_H
  52. # include <syslog.h>
  53. #endif
  54. #include <vector>
  55. #include <errno.h> // for errno
  56. #include <sstream>
  57. #include "base/commandlineflags.h" // to get the program name
  58. #include "glog/logging.h"
  59. #include "glog/raw_logging.h"
  60. #include "base/googleinit.h"
  61. #ifdef HAVE_STACKTRACE
  62. # include "stacktrace.h"
  63. #endif
  64. using std::string;
  65. using std::vector;
  66. using std::ostrstream;
  67. using std::setw;
  68. using std::setfill;
  69. using std::hex;
  70. using std::dec;
  71. using std::min;
  72. using std::ostream;
  73. using std::ostringstream;
  74. using std::strstream;
  75. // There is no thread annotation support.
  76. #define EXCLUSIVE_LOCKS_REQUIRED(mu)
  77. static bool BoolFromEnv(const char *varname, bool defval) {
  78. const char* const valstr = getenv(varname);
  79. if (!valstr) {
  80. return defval;
  81. }
  82. return memchr("tTyY1\0", valstr[0], 6) != NULL;
  83. }
  84. GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
  85. "log messages go to stderr instead of logfiles");
  86. GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
  87. "log messages go to stderr in addition to logfiles");
  88. #ifdef OS_LINUX
  89. GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
  90. "Logs can grow very quickly and they are rarely read before they "
  91. "need to be evicted from memory. Instead, drop them from memory "
  92. "as soon as they are flushed to disk.");
  93. _START_GOOGLE_NAMESPACE_
  94. namespace logging {
  95. static const int64 kPageSize = getpagesize();
  96. }
  97. _END_GOOGLE_NAMESPACE_
  98. #endif
  99. // By default, errors (including fatal errors) get logged to stderr as
  100. // well as the file.
  101. //
  102. // The default is ERROR instead of FATAL so that users can see problems
  103. // when they run a program without having to look in another file.
  104. DEFINE_int32(stderrthreshold,
  105. GOOGLE_NAMESPACE::ERROR,
  106. "log messages at or above this level are copied to stderr in "
  107. "addition to logfiles. This flag obsoletes --alsologtostderr.");
  108. GLOG_DEFINE_string(alsologtoemail, "",
  109. "log messages go to these email addresses "
  110. "in addition to logfiles");
  111. GLOG_DEFINE_bool(log_prefix, true,
  112. "Prepend the log prefix to the start of each log line");
  113. GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
  114. "actually get logged anywhere");
  115. GLOG_DEFINE_int32(logbuflevel, 0,
  116. "Buffer log messages logged at this level or lower"
  117. " (-1 means don't buffer; 0 means buffer INFO only;"
  118. " ...)");
  119. GLOG_DEFINE_int32(logbufsecs, 30,
  120. "Buffer log messages for at most this many seconds");
  121. GLOG_DEFINE_int32(logemaillevel, 999,
  122. "Email log messages logged at this level or higher"
  123. " (0 means email all; 3 means email FATAL only;"
  124. " ...)");
  125. GLOG_DEFINE_string(logmailer, "/bin/mail",
  126. "Mailer used to send logging email");
  127. // Compute the default value for --log_dir
  128. static const char* DefaultLogDir() {
  129. const char* env;
  130. env = getenv("GOOGLE_LOG_DIR");
  131. if (env != NULL && env[0] != '\0') {
  132. return env;
  133. }
  134. env = getenv("TEST_TMPDIR");
  135. if (env != NULL && env[0] != '\0') {
  136. return env;
  137. }
  138. return "";
  139. }
  140. GLOG_DEFINE_string(log_dir, DefaultLogDir(),
  141. "If specified, logfiles are written into this directory instead "
  142. "of the default logging directory.");
  143. GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
  144. "files in this directory");
  145. GLOG_DEFINE_int32(max_log_size, 1800,
  146. "approx. maximum log file size (in MB). A value of 0 will "
  147. "be silently overridden to 1.");
  148. GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
  149. "Stop attempting to log to disk if the disk is full.");
  150. GLOG_DEFINE_string(log_backtrace_at, "",
  151. "Emit a backtrace when logging at file:linenum.");
  152. // TODO(hamaji): consider windows
  153. #define PATH_SEPARATOR '/'
  154. static void GetHostName(string* hostname) {
  155. #if defined(HAVE_SYS_UTSNAME_H)
  156. struct utsname buf;
  157. if (0 != uname(&buf)) {
  158. // ensure null termination on failure
  159. *buf.nodename = '\0';
  160. }
  161. *hostname = buf.nodename;
  162. #elif defined(OS_WINDOWS)
  163. char buf[MAX_COMPUTERNAME_LENGTH + 1];
  164. DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
  165. if (GetComputerNameA(buf, &len)) {
  166. *hostname = buf;
  167. } else {
  168. hostname->clear();
  169. }
  170. #else
  171. # warning There is no way to retrieve the host name.
  172. *hostname = "(unknown)";
  173. #endif
  174. }
  175. _START_GOOGLE_NAMESPACE_
  176. // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
  177. static int32 MaxLogSize() {
  178. return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
  179. }
  180. // A mutex that allows only one thread to log at a time, to keep things from
  181. // getting jumbled. Some other very uncommon logging operations (like
  182. // changing the destination file for log messages of a given severity) also
  183. // lock this mutex. Please be sure that anybody who might possibly need to
  184. // lock it does so.
  185. static Mutex log_mutex;
  186. // Number of messages sent at each severity. Under log_mutex.
  187. int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
  188. // Globally disable log writing (if disk is full)
  189. static bool stop_writing = false;
  190. const char*const LogSeverityNames[NUM_SEVERITIES] = {
  191. "INFO", "WARNING", "ERROR", "FATAL"
  192. };
  193. // Has the user called SetExitOnDFatal(true)?
  194. static bool exit_on_dfatal = true;
  195. const char* GetLogSeverityName(LogSeverity severity) {
  196. return LogSeverityNames[severity];
  197. }
  198. static bool SendEmailInternal(const char*dest, const char *subject,
  199. const char*body, bool use_logging);
  200. base::Logger::~Logger() {
  201. }
  202. namespace {
  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. virtual void Write(bool force_flush, // Should we force a flush here?
  209. time_t timestamp, // Timestamp for this entry
  210. const char* message,
  211. int message_len);
  212. // Configuration options
  213. void SetBasename(const char* basename);
  214. void SetExtension(const char* ext);
  215. void SetSymlinkBasename(const char* symlink_basename);
  216. // Normal flushing routine
  217. virtual void Flush();
  218. // It is the actual file length for the system loggers,
  219. // i.e., INFO, ERROR, etc.
  220. virtual uint32 LogSize() {
  221. MutexLock l(&lock_);
  222. return file_length_;
  223. }
  224. // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
  225. // can avoid grabbing a lock. Usually Flush() calls it after
  226. // acquiring lock_.
  227. void FlushUnlocked();
  228. private:
  229. static const uint32 kRolloverAttemptFrequency = 0x20;
  230. Mutex lock_;
  231. bool base_filename_selected_;
  232. string base_filename_;
  233. string symlink_basename_;
  234. string filename_extension_; // option users can specify (eg to add port#)
  235. FILE* file_;
  236. LogSeverity severity_;
  237. uint32 bytes_since_flush_;
  238. uint32 file_length_;
  239. unsigned int rollover_attempt_;
  240. int64 next_flush_time_; // cycle count at which to flush log
  241. // Actually create a logfile using the value of base_filename_ and the
  242. // supplied argument time_pid_string
  243. // REQUIRES: lock_ is held
  244. bool CreateLogfile(const char* time_pid_string);
  245. };
  246. } // namespace
  247. class LogDestination {
  248. public:
  249. friend class LogMessage;
  250. friend void ReprintFatalMessage();
  251. friend base::Logger* base::GetLogger(LogSeverity);
  252. friend void base::SetLogger(LogSeverity, base::Logger*);
  253. // These methods are just forwarded to by their global versions.
  254. static void SetLogDestination(LogSeverity severity,
  255. const char* base_filename);
  256. static void SetLogSymlink(LogSeverity severity,
  257. const char* symlink_basename);
  258. static void AddLogSink(LogSink *destination);
  259. static void RemoveLogSink(LogSink *destination);
  260. static void SetLogFilenameExtension(const char* filename_extension);
  261. static void SetStderrLogging(LogSeverity min_severity);
  262. static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
  263. static void LogToStderr();
  264. // Flush all log files that are at least at the given severity level
  265. static void FlushLogFiles(int min_severity);
  266. static void FlushLogFilesUnsafe(int min_severity);
  267. // we set the maximum size of our packet to be 1400, the logic being
  268. // to prevent fragmentation.
  269. // Really this number is arbitrary.
  270. static const int kNetworkBytes = 1400;
  271. static const string& hostname();
  272. static void DeleteLogDestinations();
  273. private:
  274. LogDestination(LogSeverity severity, const char* base_filename);
  275. ~LogDestination() { }
  276. // Take a log message of a particular severity and log it to stderr
  277. // iff it's of a high enough severity to deserve it.
  278. static void MaybeLogToStderr(LogSeverity severity, const char* message,
  279. size_t len);
  280. // Take a log message of a particular severity and log it to email
  281. // iff it's of a high enough severity to deserve it.
  282. static void MaybeLogToEmail(LogSeverity severity, const char* message,
  283. size_t len);
  284. // Take a log message of a particular severity and log it to a file
  285. // iff the base filename is not "" (which means "don't log to me")
  286. static void MaybeLogToLogfile(LogSeverity severity,
  287. time_t timestamp,
  288. const char* message, size_t len);
  289. // Take a log message of a particular severity and log it to the file
  290. // for that severity and also for all files with severity less than
  291. // this severity.
  292. static void LogToAllLogfiles(LogSeverity severity,
  293. time_t timestamp,
  294. const char* message, size_t len);
  295. // Send logging info to all registered sinks.
  296. static void LogToSinks(LogSeverity severity,
  297. const char *full_filename,
  298. const char *base_filename,
  299. int line,
  300. const struct ::tm* tm_time,
  301. const char* message,
  302. size_t message_len);
  303. // Wait for all registered sinks via WaitTillSent
  304. // including the optional one in "data".
  305. static void WaitForSinks(LogMessage::LogMessageData* data);
  306. static LogDestination* log_destination(LogSeverity severity);
  307. LogFileObject fileobject_;
  308. base::Logger* logger_; // Either &fileobject_, or wrapper around it
  309. static LogDestination* log_destinations_[NUM_SEVERITIES];
  310. static LogSeverity email_logging_severity_;
  311. static string addresses_;
  312. static string hostname_;
  313. // arbitrary global logging destinations.
  314. static vector<LogSink*>* sinks_;
  315. // Protects the vector sinks_,
  316. // but not the LogSink objects its elements reference.
  317. static Mutex sink_mutex_;
  318. // Disallow
  319. LogDestination(const LogDestination&);
  320. LogDestination& operator=(const LogDestination&);
  321. };
  322. // Errors do not get logged to email by default.
  323. LogSeverity LogDestination::email_logging_severity_ = 99999;
  324. string LogDestination::addresses_;
  325. string LogDestination::hostname_;
  326. vector<LogSink*>* LogDestination::sinks_ = NULL;
  327. Mutex LogDestination::sink_mutex_;
  328. /* static */
  329. const string& LogDestination::hostname() {
  330. if (hostname_.empty()) {
  331. GetHostName(&hostname_);
  332. if (hostname_.empty()) {
  333. hostname_ = "(unknown)";
  334. }
  335. }
  336. return hostname_;
  337. }
  338. LogDestination::LogDestination(LogSeverity severity,
  339. const char* base_filename)
  340. : fileobject_(severity, base_filename),
  341. logger_(&fileobject_) {
  342. }
  343. inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
  344. // assume we have the log_mutex or we simply don't care
  345. // about it
  346. for (int i = min_severity; i < NUM_SEVERITIES; i++) {
  347. LogDestination* log = log_destination(i);
  348. if (log != NULL) {
  349. // Flush the base fileobject_ logger directly instead of going
  350. // through any wrappers to reduce chance of deadlock.
  351. log->fileobject_.FlushUnlocked();
  352. }
  353. }
  354. }
  355. inline void LogDestination::FlushLogFiles(int min_severity) {
  356. // Prevent any subtle race conditions by wrapping a mutex lock around
  357. // all this stuff.
  358. MutexLock l(&log_mutex);
  359. for (int i = min_severity; i < NUM_SEVERITIES; i++) {
  360. LogDestination* log = log_destination(i);
  361. if (log != NULL) {
  362. log->logger_->Flush();
  363. }
  364. }
  365. }
  366. inline void LogDestination::SetLogDestination(LogSeverity severity,
  367. const char* base_filename) {
  368. assert(severity >= 0 && severity < NUM_SEVERITIES);
  369. // Prevent any subtle race conditions by wrapping a mutex lock around
  370. // all this stuff.
  371. MutexLock l(&log_mutex);
  372. log_destination(severity)->fileobject_.SetBasename(base_filename);
  373. }
  374. inline void LogDestination::SetLogSymlink(LogSeverity severity,
  375. const char* symlink_basename) {
  376. CHECK_GE(severity, 0);
  377. CHECK_LT(severity, NUM_SEVERITIES);
  378. MutexLock l(&log_mutex);
  379. log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
  380. }
  381. inline void LogDestination::AddLogSink(LogSink *destination) {
  382. // Prevent any subtle race conditions by wrapping a mutex lock around
  383. // all this stuff.
  384. MutexLock l(&sink_mutex_);
  385. if (!sinks_) sinks_ = new vector<LogSink*>;
  386. sinks_->push_back(destination);
  387. }
  388. inline void LogDestination::RemoveLogSink(LogSink *destination) {
  389. // Prevent any subtle race conditions by wrapping a mutex lock around
  390. // all this stuff.
  391. MutexLock l(&sink_mutex_);
  392. // This doesn't keep the sinks in order, but who cares?
  393. if (sinks_) {
  394. for (int i = sinks_->size() - 1; i >= 0; i--) {
  395. if ((*sinks_)[i] == destination) {
  396. (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
  397. sinks_->pop_back();
  398. break;
  399. }
  400. }
  401. }
  402. }
  403. inline void LogDestination::SetLogFilenameExtension(const char* ext) {
  404. // Prevent any subtle race conditions by wrapping a mutex lock around
  405. // all this stuff.
  406. MutexLock l(&log_mutex);
  407. for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
  408. log_destination(severity)->fileobject_.SetExtension(ext);
  409. }
  410. }
  411. inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
  412. assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
  413. // Prevent any subtle race conditions by wrapping a mutex lock around
  414. // all this stuff.
  415. MutexLock l(&log_mutex);
  416. FLAGS_stderrthreshold = min_severity;
  417. }
  418. inline void LogDestination::LogToStderr() {
  419. // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
  420. // SetLogDestination already do the locking!
  421. SetStderrLogging(0); // thus everything is "also" logged to stderr
  422. for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
  423. SetLogDestination(i, ""); // "" turns off logging to a logfile
  424. }
  425. }
  426. inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
  427. const char* addresses) {
  428. assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
  429. // Prevent any subtle race conditions by wrapping a mutex lock around
  430. // all this stuff.
  431. MutexLock l(&log_mutex);
  432. LogDestination::email_logging_severity_ = min_severity;
  433. LogDestination::addresses_ = addresses;
  434. }
  435. static void WriteToStderr(const char* message, size_t len) {
  436. // Avoid using cerr from this module since we may get called during
  437. // exit code, and cerr may be partially or fully destroyed by then.
  438. fwrite(message, len, 1, stderr);
  439. }
  440. inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
  441. const char* message, size_t len) {
  442. if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
  443. WriteToStderr(message, len);
  444. #ifdef OS_WINDOWS
  445. // On Windows, also output to the debugger
  446. ::OutputDebugStringA(string(message,len).c_str());
  447. #endif
  448. }
  449. }
  450. inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
  451. const char* message, size_t len) {
  452. if (severity >= email_logging_severity_ ||
  453. severity >= FLAGS_logemaillevel) {
  454. string to(FLAGS_alsologtoemail);
  455. if (!addresses_.empty()) {
  456. if (!to.empty()) {
  457. to += ",";
  458. }
  459. to += addresses_;
  460. }
  461. const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
  462. glog_internal_namespace_::ProgramInvocationShortName());
  463. string body(hostname());
  464. body += "\n\n";
  465. body.append(message, len);
  466. // should NOT use SendEmail(). The caller of this function holds the
  467. // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
  468. // acquire the log_mutex object. Use SendEmailInternal() and set
  469. // use_logging to false.
  470. SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
  471. }
  472. }
  473. inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
  474. time_t timestamp,
  475. const char* message,
  476. size_t len) {
  477. const bool should_flush = severity > FLAGS_logbuflevel;
  478. LogDestination* destination = log_destination(severity);
  479. destination->logger_->Write(should_flush, timestamp, message, len);
  480. }
  481. inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
  482. time_t timestamp,
  483. const char* message,
  484. size_t len) {
  485. if ( FLAGS_logtostderr ) // global flag: never log to file
  486. WriteToStderr(message, len);
  487. else
  488. for (int i = severity; i >= 0; --i)
  489. LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
  490. }
  491. inline void LogDestination::LogToSinks(LogSeverity severity,
  492. const char *full_filename,
  493. const char *base_filename,
  494. int line,
  495. const struct ::tm* tm_time,
  496. const char* message,
  497. size_t message_len) {
  498. ReaderMutexLock l(&sink_mutex_);
  499. if (sinks_) {
  500. for (int i = sinks_->size() - 1; i >= 0; i--) {
  501. (*sinks_)[i]->send(severity, full_filename, base_filename,
  502. line, tm_time, message, message_len);
  503. }
  504. }
  505. }
  506. inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
  507. ReaderMutexLock l(&sink_mutex_);
  508. if (sinks_) {
  509. for (int i = sinks_->size() - 1; i >= 0; i--) {
  510. (*sinks_)[i]->WaitTillSent();
  511. }
  512. }
  513. const bool send_to_sink =
  514. (data->send_method_ == &LogMessage::SendToSink) ||
  515. (data->send_method_ == &LogMessage::SendToSinkAndLog);
  516. if (send_to_sink && data->sink_ != NULL) {
  517. data->sink_->WaitTillSent();
  518. }
  519. }
  520. LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
  521. inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
  522. assert(severity >=0 && severity < NUM_SEVERITIES);
  523. if (!log_destinations_[severity]) {
  524. log_destinations_[severity] = new LogDestination(severity, NULL);
  525. }
  526. return log_destinations_[severity];
  527. }
  528. void LogDestination::DeleteLogDestinations() {
  529. for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
  530. delete log_destinations_[severity];
  531. log_destinations_[severity] = NULL;
  532. }
  533. }
  534. namespace {
  535. LogFileObject::LogFileObject(LogSeverity severity,
  536. const char* base_filename)
  537. : base_filename_selected_(base_filename != NULL),
  538. base_filename_((base_filename != NULL) ? base_filename : ""),
  539. symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
  540. filename_extension_(),
  541. file_(NULL),
  542. severity_(severity),
  543. bytes_since_flush_(0),
  544. file_length_(0),
  545. rollover_attempt_(kRolloverAttemptFrequency-1),
  546. next_flush_time_(0) {
  547. assert(severity >= 0);
  548. assert(severity < NUM_SEVERITIES);
  549. }
  550. LogFileObject::~LogFileObject() {
  551. MutexLock l(&lock_);
  552. if (file_ != NULL) {
  553. fclose(file_);
  554. file_ = NULL;
  555. }
  556. }
  557. void LogFileObject::SetBasename(const char* basename) {
  558. MutexLock l(&lock_);
  559. base_filename_selected_ = true;
  560. if (base_filename_ != basename) {
  561. // Get rid of old log file since we are changing names
  562. if (file_ != NULL) {
  563. fclose(file_);
  564. file_ = NULL;
  565. rollover_attempt_ = kRolloverAttemptFrequency-1;
  566. }
  567. base_filename_ = basename;
  568. }
  569. }
  570. void LogFileObject::SetExtension(const char* ext) {
  571. MutexLock l(&lock_);
  572. if (filename_extension_ != ext) {
  573. // Get rid of old log file since we are changing names
  574. if (file_ != NULL) {
  575. fclose(file_);
  576. file_ = NULL;
  577. rollover_attempt_ = kRolloverAttemptFrequency-1;
  578. }
  579. filename_extension_ = ext;
  580. }
  581. }
  582. void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
  583. MutexLock l(&lock_);
  584. symlink_basename_ = symlink_basename;
  585. }
  586. void LogFileObject::Flush() {
  587. MutexLock l(&lock_);
  588. FlushUnlocked();
  589. }
  590. void LogFileObject::FlushUnlocked(){
  591. if (file_ != NULL) {
  592. fflush(file_);
  593. bytes_since_flush_ = 0;
  594. }
  595. // Figure out when we are due for another flush.
  596. const int64 next = (FLAGS_logbufsecs
  597. * static_cast<int64>(1000000)); // in usec
  598. next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
  599. }
  600. bool LogFileObject::CreateLogfile(const char* time_pid_string) {
  601. string string_filename = base_filename_+filename_extension_+
  602. time_pid_string;
  603. const char* filename = string_filename.c_str();
  604. int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664);
  605. if (fd == -1) return false;
  606. #ifdef HAVE_FCNTL
  607. // Mark the file close-on-exec. We don't really care if this fails
  608. fcntl(fd, F_SETFD, FD_CLOEXEC);
  609. #endif
  610. file_ = fdopen(fd, "a"); // Make a FILE*.
  611. if (file_ == NULL) { // Man, we're screwed!
  612. close(fd);
  613. unlink(filename); // Erase the half-baked evidence: an unusable log file
  614. return false;
  615. }
  616. // We try to create a symlink called <program_name>.<severity>,
  617. // which is easier to use. (Every time we create a new logfile,
  618. // we destroy the old symlink and create a new one, so it always
  619. // points to the latest logfile.) If it fails, we're sad but it's
  620. // no error.
  621. if (!symlink_basename_.empty()) {
  622. // take directory from filename
  623. const char* slash = strrchr(filename, PATH_SEPARATOR);
  624. const string linkname =
  625. symlink_basename_ + '.' + LogSeverityNames[severity_];
  626. string linkpath;
  627. if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
  628. linkpath += linkname;
  629. unlink(linkpath.c_str()); // delete old one if it exists
  630. // We must have unistd.h.
  631. #ifdef HAVE_UNISTD_H
  632. // Make the symlink be relative (in the same dir) so that if the
  633. // entire log directory gets relocated the link is still valid.
  634. const char *linkdest = slash ? (slash + 1) : filename;
  635. if (symlink(linkdest, linkpath.c_str()) != 0) {
  636. // silently ignore failures
  637. }
  638. // Make an additional link to the log file in a place specified by
  639. // FLAGS_log_link, if indicated
  640. if (!FLAGS_log_link.empty()) {
  641. linkpath = FLAGS_log_link + "/" + linkname;
  642. unlink(linkpath.c_str()); // delete old one if it exists
  643. if (symlink(filename, linkpath.c_str()) != 0) {
  644. // silently ignore failures
  645. }
  646. }
  647. #endif
  648. }
  649. return true; // Everything worked
  650. }
  651. void LogFileObject::Write(bool force_flush,
  652. time_t timestamp,
  653. const char* message,
  654. int message_len) {
  655. MutexLock l(&lock_);
  656. // We don't log if the base_name_ is "" (which means "don't write")
  657. if (base_filename_selected_ && base_filename_.empty()) {
  658. return;
  659. }
  660. if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
  661. PidHasChanged()) {
  662. if (file_ != NULL) fclose(file_);
  663. file_ = NULL;
  664. file_length_ = bytes_since_flush_ = 0;
  665. rollover_attempt_ = kRolloverAttemptFrequency-1;
  666. }
  667. // If there's no destination file, make one before outputting
  668. if (file_ == NULL) {
  669. // Try to rollover the log file every 32 log messages. The only time
  670. // this could matter would be when we have trouble creating the log
  671. // file. If that happens, we'll lose lots of log messages, of course!
  672. if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
  673. rollover_attempt_ = 0;
  674. struct ::tm tm_time;
  675. localtime_r(&timestamp, &tm_time);
  676. // The logfile's filename will have the date/time & pid in it
  677. char time_pid_string[256]; // More than enough chars for time, pid, \0
  678. ostrstream time_pid_stream(time_pid_string, sizeof(time_pid_string));
  679. time_pid_stream.fill('0');
  680. time_pid_stream << 1900+tm_time.tm_year
  681. << setw(2) << 1+tm_time.tm_mon
  682. << setw(2) << tm_time.tm_mday
  683. << '-'
  684. << setw(2) << tm_time.tm_hour
  685. << setw(2) << tm_time.tm_min
  686. << setw(2) << tm_time.tm_sec
  687. << '.'
  688. << GetMainThreadPid()
  689. << '\0';
  690. if (base_filename_selected_) {
  691. if (!CreateLogfile(time_pid_string)) {
  692. perror("Could not create log file");
  693. fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", time_pid_string);
  694. return;
  695. }
  696. } else {
  697. // If no base filename for logs of this severity has been set, use a
  698. // default base filename of
  699. // "<program name>.<hostname>.<user name>.log.<severity level>.". So
  700. // logfiles will have names like
  701. // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
  702. // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
  703. // and 4354 is the pid of the logging process. The date & time reflect
  704. // when the file was created for output.
  705. //
  706. // Where does the file get put? Successively try the directories
  707. // "/tmp", and "."
  708. string stripped_filename(
  709. glog_internal_namespace_::ProgramInvocationShortName());
  710. string hostname;
  711. GetHostName(&hostname);
  712. string uidname = MyUserName();
  713. // We should not call CHECK() here because this function can be
  714. // called after holding on to log_mutex. We don't want to
  715. // attempt to hold on to the same mutex, and get into a
  716. // deadlock. Simply use a name like invalid-user.
  717. if (uidname.empty()) uidname = "invalid-user";
  718. stripped_filename = stripped_filename+'.'+hostname+'.'
  719. +uidname+".log."
  720. +LogSeverityNames[severity_]+'.';
  721. // We're going to (potentially) try to put logs in several different dirs
  722. const vector<string> & log_dirs = GetLoggingDirectories();
  723. // Go through the list of dirs, and try to create the log file in each
  724. // until we succeed or run out of options
  725. bool success = false;
  726. for (vector<string>::const_iterator dir = log_dirs.begin();
  727. dir != log_dirs.end();
  728. ++dir) {
  729. base_filename_ = *dir + "/" + stripped_filename;
  730. if ( CreateLogfile(time_pid_string) ) {
  731. success = true;
  732. break;
  733. }
  734. }
  735. // If we never succeeded, we have to give up
  736. if ( success == false ) {
  737. perror("Could not create logging file");
  738. fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", time_pid_string);
  739. return;
  740. }
  741. }
  742. // Write a header message into the log file
  743. char file_header_string[512]; // Enough chars for time and binary info
  744. ostrstream file_header_stream(file_header_string,
  745. sizeof(file_header_string));
  746. file_header_stream.fill('0');
  747. file_header_stream << "Log file created at: "
  748. << 1900+tm_time.tm_year << '/'
  749. << setw(2) << 1+tm_time.tm_mon << '/'
  750. << setw(2) << tm_time.tm_mday
  751. << ' '
  752. << setw(2) << tm_time.tm_hour << ':'
  753. << setw(2) << tm_time.tm_min << ':'
  754. << setw(2) << tm_time.tm_sec << '\n'
  755. << "Running on machine: "
  756. << LogDestination::hostname() << '\n'
  757. << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
  758. << "threadid file:line] msg" << '\n'
  759. << '\0';
  760. int header_len = strlen(file_header_string);
  761. fwrite(file_header_string, 1, header_len, file_);
  762. file_length_ += header_len;
  763. bytes_since_flush_ += header_len;
  764. }
  765. // Write to LOG file
  766. if ( !stop_writing ) {
  767. // fwrite() doesn't return an error when the disk is full, for
  768. // messages that are less than 4096 bytes. When the disk is full,
  769. // it returns the message length for messages that are less than
  770. // 4096 bytes. fwrite() returns 4096 for message lengths that are
  771. // greater than 4096, thereby indicating an error.
  772. errno = 0;
  773. fwrite(message, 1, message_len, file_);
  774. if ( FLAGS_stop_logging_if_full_disk &&
  775. errno == ENOSPC ) { // disk full, stop writing to disk
  776. stop_writing = true; // until the disk is
  777. return;
  778. } else {
  779. file_length_ += message_len;
  780. bytes_since_flush_ += message_len;
  781. }
  782. } else {
  783. if ( CycleClock_Now() >= next_flush_time_ )
  784. stop_writing = false; // check to see if disk has free space.
  785. return; // no need to flush
  786. }
  787. // See important msgs *now*. Also, flush logs at least every 10^6 chars,
  788. // or every "FLAGS_logbufsecs" seconds.
  789. if ( force_flush ||
  790. (bytes_since_flush_ >= 1000000) ||
  791. (CycleClock_Now() >= next_flush_time_) ) {
  792. FlushUnlocked();
  793. #ifdef OS_LINUX
  794. if (FLAGS_drop_log_memory) {
  795. if (file_length_ >= logging::kPageSize) {
  796. // don't evict the most recent page
  797. uint32 len = file_length_ & ~(logging::kPageSize - 1);
  798. posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
  799. }
  800. }
  801. #endif
  802. }
  803. }
  804. } // namespace
  805. // An arbitrary limit on the length of a single log message. This
  806. // is so that streaming can be done more efficiently.
  807. const size_t LogMessage::kMaxLogMessageLen = 30000;
  808. // Static log data space to avoid alloc failures in a LOG(FATAL)
  809. //
  810. // Since multiple threads may call LOG(FATAL), and we want to preserve
  811. // the data from the first call, we allocate two sets of space. One
  812. // for exclusive use by the first thread, and one for shared use by
  813. // all other threads.
  814. static Mutex fatal_msg_lock;
  815. static CrashReason crash_reason;
  816. static bool fatal_msg_exclusive = true;
  817. static char fatal_msg_buf_exclusive[LogMessage::kMaxLogMessageLen+1];
  818. static char fatal_msg_buf_shared[LogMessage::kMaxLogMessageLen+1];
  819. static LogMessage::LogStream fatal_msg_stream_exclusive(
  820. fatal_msg_buf_exclusive, LogMessage::kMaxLogMessageLen, 0);
  821. static LogMessage::LogStream fatal_msg_stream_shared(
  822. fatal_msg_buf_shared, LogMessage::kMaxLogMessageLen, 0);
  823. LogMessage::LogMessageData LogMessage::fatal_msg_data_exclusive_;
  824. LogMessage::LogMessageData LogMessage::fatal_msg_data_shared_;
  825. LogMessage::LogMessageData::~LogMessageData() {
  826. delete[] buf_;
  827. delete stream_alloc_;
  828. }
  829. LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
  830. int ctr, void (LogMessage::*send_method)()) {
  831. Init(file, line, severity, send_method);
  832. data_->stream_->set_ctr(ctr);
  833. }
  834. LogMessage::LogMessage(const char* file, int line,
  835. const CheckOpString& result) {
  836. Init(file, line, FATAL, &LogMessage::SendToLog);
  837. stream() << "Check failed: " << (*result.str_) << " ";
  838. }
  839. LogMessage::LogMessage(const char* file, int line) {
  840. Init(file, line, INFO, &LogMessage::SendToLog);
  841. }
  842. LogMessage::LogMessage(const char* file, int line, LogSeverity severity) {
  843. Init(file, line, severity, &LogMessage::SendToLog);
  844. }
  845. LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
  846. LogSink* sink, bool also_send_to_log) {
  847. Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
  848. &LogMessage::SendToSink);
  849. data_->sink_ = sink; // override Init()'s setting to NULL
  850. }
  851. LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
  852. vector<string> *outvec) {
  853. Init(file, line, severity, &LogMessage::SaveOrSendToLog);
  854. data_->outvec_ = outvec; // override Init()'s setting to NULL
  855. }
  856. LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
  857. string *message) {
  858. Init(file, line, severity, &LogMessage::WriteToStringAndLog);
  859. data_->message_ = message; // override Init()'s setting to NULL
  860. }
  861. void LogMessage::Init(const char* file,
  862. int line,
  863. LogSeverity severity,
  864. void (LogMessage::*send_method)()) {
  865. allocated_ = NULL;
  866. if (severity != FATAL || !exit_on_dfatal) {
  867. allocated_ = new LogMessageData();
  868. data_ = allocated_;
  869. data_->buf_ = new char[kMaxLogMessageLen+1];
  870. data_->message_text_ = data_->buf_;
  871. data_->stream_alloc_ =
  872. new LogStream(data_->message_text_, kMaxLogMessageLen, 0);
  873. data_->stream_ = data_->stream_alloc_;
  874. data_->first_fatal_ = false;
  875. } else {
  876. MutexLock l(&fatal_msg_lock);
  877. if (fatal_msg_exclusive) {
  878. fatal_msg_exclusive = false;
  879. data_ = &fatal_msg_data_exclusive_;
  880. data_->message_text_ = fatal_msg_buf_exclusive;
  881. data_->stream_ = &fatal_msg_stream_exclusive;
  882. data_->first_fatal_ = true;
  883. } else {
  884. data_ = &fatal_msg_data_shared_;
  885. data_->message_text_ = fatal_msg_buf_shared;
  886. data_->stream_ = &fatal_msg_stream_shared;
  887. data_->first_fatal_ = false;
  888. }
  889. data_->stream_alloc_ = NULL;
  890. }
  891. stream().fill('0');
  892. data_->preserved_errno_ = errno;
  893. data_->severity_ = severity;
  894. data_->line_ = line;
  895. data_->send_method_ = send_method;
  896. data_->sink_ = NULL;
  897. data_->outvec_ = NULL;
  898. WallTime now = WallTime_Now();
  899. data_->timestamp_ = static_cast<time_t>(now);
  900. localtime_r(&data_->timestamp_, &data_->tm_time_);
  901. int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
  902. RawLog__SetLastTime(data_->tm_time_, usecs);
  903. data_->num_chars_to_log_ = 0;
  904. data_->num_chars_to_syslog_ = 0;
  905. data_->basename_ = const_basename(file);
  906. data_->fullname_ = file;
  907. data_->has_been_flushed_ = false;
  908. // If specified, prepend a prefix to each line. For example:
  909. // I1018 160715 f5d4fbb0 logging.cc:1153]
  910. // (log level, GMT month, date, time, thread_id, file basename, line)
  911. // We exclude the thread_id for the default thread.
  912. if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
  913. stream() << LogSeverityNames[severity][0]
  914. << setw(2) << 1+data_->tm_time_.tm_mon
  915. << setw(2) << data_->tm_time_.tm_mday
  916. << ' '
  917. << setw(2) << data_->tm_time_.tm_hour << ':'
  918. << setw(2) << data_->tm_time_.tm_min << ':'
  919. << setw(2) << data_->tm_time_.tm_sec << "."
  920. << setw(6) << usecs
  921. << ' '
  922. << setfill(' ') << setw(5)
  923. << static_cast<unsigned int>(GetTID()) << setfill('0')
  924. << ' '
  925. << data_->basename_ << ':' << data_->line_ << "] ";
  926. }
  927. data_->num_prefix_chars_ = data_->stream_->pcount();
  928. if (!FLAGS_log_backtrace_at.empty()) {
  929. char fileline[128];
  930. snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
  931. #ifdef HAVE_STACKTRACE
  932. if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
  933. string stacktrace;
  934. DumpStackTraceToString(&stacktrace);
  935. stream() << " (stacktrace:\n" << stacktrace << ") ";
  936. }
  937. #endif
  938. }
  939. }
  940. LogMessage::~LogMessage() {
  941. Flush();
  942. delete allocated_;
  943. }
  944. // Flush buffered message, called by the destructor, or any other function
  945. // that needs to synchronize the log.
  946. void LogMessage::Flush() {
  947. if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
  948. return;
  949. data_->num_chars_to_log_ = data_->stream_->pcount();
  950. data_->num_chars_to_syslog_ =
  951. data_->num_chars_to_log_ - data_->num_prefix_chars_;
  952. // Do we need to add a \n to the end of this message?
  953. bool append_newline =
  954. (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
  955. char original_final_char = '\0';
  956. // If we do need to add a \n, we'll do it by violating the memory of the
  957. // ostrstream buffer. This is quick, and we'll make sure to undo our
  958. // modification before anything else is done with the ostrstream. It
  959. // would be preferable not to do things this way, but it seems to be
  960. // the best way to deal with this.
  961. if (append_newline) {
  962. original_final_char = data_->message_text_[data_->num_chars_to_log_];
  963. data_->message_text_[data_->num_chars_to_log_++] = '\n';
  964. }
  965. // Prevent any subtle race conditions by wrapping a mutex lock around
  966. // the actual logging action per se.
  967. {
  968. MutexLock l(&log_mutex);
  969. (this->*(data_->send_method_))();
  970. ++num_messages_[static_cast<int>(data_->severity_)];
  971. }
  972. LogDestination::WaitForSinks(data_);
  973. if (append_newline) {
  974. // Fix the ostrstream back how it was before we screwed with it.
  975. // It's 99.44% certain that we don't need to worry about doing this.
  976. data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
  977. }
  978. // If errno was already set before we enter the logging call, we'll
  979. // set it back to that value when we return from the logging call.
  980. // It happens often that we log an error message after a syscall
  981. // failure, which can potentially set the errno to some other
  982. // values. We would like to preserve the original errno.
  983. if (data_->preserved_errno_ != 0) {
  984. errno = data_->preserved_errno_;
  985. }
  986. // Note that this message is now safely logged. If we're asked to flush
  987. // again, as a result of destruction, say, we'll do nothing on future calls.
  988. data_->has_been_flushed_ = true;
  989. }
  990. // Copy of first FATAL log message so that we can print it out again
  991. // after all the stack traces. To preserve legacy behavior, we don't
  992. // use fatal_msg_buf_exclusive.
  993. static time_t fatal_time;
  994. static char fatal_message[256];
  995. void ReprintFatalMessage() {
  996. if (fatal_message[0]) {
  997. const int n = strlen(fatal_message);
  998. if (!FLAGS_logtostderr) {
  999. // Also write to stderr
  1000. WriteToStderr(fatal_message, n);
  1001. }
  1002. LogDestination::LogToAllLogfiles(ERROR, fatal_time, fatal_message, n);
  1003. }
  1004. }
  1005. // L >= log_mutex (callers must hold the log_mutex).
  1006. void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
  1007. static bool already_warned_before_initgoogle = false;
  1008. log_mutex.AssertHeld();
  1009. RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
  1010. data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
  1011. // Messages of a given severity get logged to lower severity logs, too
  1012. if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
  1013. const char w[] = "WARNING: Logging before InitGoogleLogging() is "
  1014. "written to STDERR\n";
  1015. WriteToStderr(w, strlen(w));
  1016. already_warned_before_initgoogle = true;
  1017. }
  1018. // global flag: never log to file if set. Also -- don't log to a
  1019. // file if we haven't parsed the command line flags to get the
  1020. // program name.
  1021. if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
  1022. WriteToStderr(data_->message_text_, data_->num_chars_to_log_);
  1023. // this could be protected by a flag if necessary.
  1024. LogDestination::LogToSinks(data_->severity_,
  1025. data_->fullname_, data_->basename_,
  1026. data_->line_, &data_->tm_time_,
  1027. data_->message_text_ + data_->num_prefix_chars_,
  1028. (data_->num_chars_to_log_ -
  1029. data_->num_prefix_chars_ - 1));
  1030. } else {
  1031. // log this message to all log files of severity <= severity_
  1032. LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
  1033. data_->message_text_,
  1034. data_->num_chars_to_log_);
  1035. LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
  1036. data_->num_chars_to_log_);
  1037. LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
  1038. data_->num_chars_to_log_);
  1039. LogDestination::LogToSinks(data_->severity_,
  1040. data_->fullname_, data_->basename_,
  1041. data_->line_, &data_->tm_time_,
  1042. data_->message_text_ + data_->num_prefix_chars_,
  1043. (data_->num_chars_to_log_
  1044. - data_->num_prefix_chars_ - 1));
  1045. // NOTE: -1 removes trailing \n
  1046. }
  1047. // If we log a FATAL message, flush all the log destinations, then toss
  1048. // a signal for others to catch. We leave the logs in a state that
  1049. // someone else can use them (as long as they flush afterwards)
  1050. if (data_->severity_ == FATAL && exit_on_dfatal) {
  1051. if (data_->first_fatal_) {
  1052. // Store crash information so that it is accessible from within signal
  1053. // handlers that may be invoked later.
  1054. RecordCrashReason(&crash_reason);
  1055. SetCrashReason(&crash_reason);
  1056. // Store shortened fatal message for other logs and GWQ status
  1057. const int copy = min<int>(data_->num_chars_to_log_,
  1058. sizeof(fatal_message)-1);
  1059. memcpy(fatal_message, data_->message_text_, copy);
  1060. fatal_message[copy] = '\0';
  1061. fatal_time = data_->timestamp_;
  1062. }
  1063. if (!FLAGS_logtostderr) {
  1064. for (int i = 0; i < NUM_SEVERITIES; ++i) {
  1065. if ( LogDestination::log_destinations_[i] )
  1066. LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
  1067. }
  1068. }
  1069. // release the lock that our caller (directly or indirectly)
  1070. // LogMessage::~LogMessage() grabbed so that signal handlers
  1071. // can use the logging facility. Alternately, we could add
  1072. // an entire unsafe logging interface to bypass locking
  1073. // for signal handlers but this seems simpler.
  1074. log_mutex.Unlock();
  1075. LogDestination::WaitForSinks(data_);
  1076. const char* message = "*** Check failure stack trace: ***\n";
  1077. if (write(STDERR_FILENO, message, strlen(message)) < 0) {
  1078. // Ignore errors.
  1079. }
  1080. Fail();
  1081. }
  1082. }
  1083. void LogMessage::RecordCrashReason(
  1084. glog_internal_namespace_::CrashReason* reason) {
  1085. reason->filename = fatal_msg_data_exclusive_.fullname_;
  1086. reason->line_number = fatal_msg_data_exclusive_.line_;
  1087. reason->message = fatal_msg_buf_exclusive +
  1088. fatal_msg_data_exclusive_.num_prefix_chars_;
  1089. #ifdef HAVE_STACKTRACE
  1090. // Retrieve the stack trace, omitting the logging frames that got us here.
  1091. reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
  1092. #else
  1093. reason->depth = 0;
  1094. #endif
  1095. }
  1096. static void logging_fail() {
  1097. #if defined(_DEBUG) && defined(_MSC_VER)
  1098. // When debugging on windows, avoid the obnoxious dialog and make
  1099. // it possible to continue past a LOG(FATAL) in the debugger
  1100. _asm int 3
  1101. #else
  1102. abort();
  1103. #endif
  1104. }
  1105. #ifdef HAVE___ATTRIBUTE__
  1106. GOOGLE_GLOG_DLL_DECL
  1107. void (*g_logging_fail_func)() __attribute__((noreturn)) = &logging_fail;
  1108. #else
  1109. GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)() = &logging_fail;
  1110. #endif
  1111. void InstallFailureFunction(void (*fail_func)()) {
  1112. g_logging_fail_func = fail_func;
  1113. }
  1114. void LogMessage::Fail() {
  1115. g_logging_fail_func();
  1116. }
  1117. // L >= log_mutex (callers must hold the log_mutex).
  1118. void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
  1119. if (data_->sink_ != NULL) {
  1120. RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
  1121. data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
  1122. data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
  1123. data_->line_, &data_->tm_time_,
  1124. data_->message_text_ + data_->num_prefix_chars_,
  1125. (data_->num_chars_to_log_ -
  1126. data_->num_prefix_chars_ - 1));
  1127. }
  1128. }
  1129. // L >= log_mutex (callers must hold the log_mutex).
  1130. void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
  1131. SendToSink();
  1132. SendToLog();
  1133. }
  1134. // L >= log_mutex (callers must hold the log_mutex).
  1135. void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
  1136. if (data_->outvec_ != NULL) {
  1137. RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
  1138. data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
  1139. // Omit prefix of message and trailing newline when recording in outvec_.
  1140. const char *start = data_->message_text_ + data_->num_prefix_chars_;
  1141. int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
  1142. data_->outvec_->push_back(string(start, len));
  1143. } else {
  1144. SendToLog();
  1145. }
  1146. }
  1147. void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
  1148. if (data_->message_ != NULL) {
  1149. RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
  1150. data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
  1151. // Omit prefix of message and trailing newline when writing to message_.
  1152. const char *start = data_->message_text_ + data_->num_prefix_chars_;
  1153. int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
  1154. data_->message_->assign(start, len);
  1155. }
  1156. SendToLog();
  1157. }
  1158. // L >= log_mutex (callers must hold the log_mutex).
  1159. void LogMessage::SendToSyslogAndLog() {
  1160. #ifdef HAVE_SYSLOG_H
  1161. // Before any calls to syslog(), make a single call to openlog()
  1162. static bool openlog_already_called = false;
  1163. if (!openlog_already_called) {
  1164. openlog(glog_internal_namespace_::ProgramInvocationShortName(),
  1165. LOG_CONS | LOG_NDELAY | LOG_PID,
  1166. LOG_USER);
  1167. openlog_already_called = true;
  1168. }
  1169. // This array maps Google severity levels to syslog levels
  1170. const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
  1171. syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
  1172. int(data_->num_chars_to_syslog_),
  1173. data_->message_text_ + data_->num_prefix_chars_);
  1174. SendToLog();
  1175. #else
  1176. LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
  1177. #endif
  1178. }
  1179. base::Logger* base::GetLogger(LogSeverity severity) {
  1180. MutexLock l(&log_mutex);
  1181. return LogDestination::log_destination(severity)->logger_;
  1182. }
  1183. void base::SetLogger(LogSeverity severity, base::Logger* logger) {
  1184. MutexLock l(&log_mutex);
  1185. LogDestination::log_destination(severity)->logger_ = logger;
  1186. }
  1187. // L < log_mutex. Acquires and releases mutex_.
  1188. int64 LogMessage::num_messages(int severity) {
  1189. MutexLock l(&log_mutex);
  1190. return num_messages_[severity];
  1191. }
  1192. // Output the COUNTER value. This is only valid if ostream is a
  1193. // LogStream.
  1194. ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
  1195. LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
  1196. CHECK(log == log->self());
  1197. os << log->ctr();
  1198. return os;
  1199. }
  1200. ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
  1201. LogSeverity severity, int ctr,
  1202. void (LogMessage::*send_method)())
  1203. : LogMessage(file, line, severity, ctr, send_method) {
  1204. }
  1205. ErrnoLogMessage::~ErrnoLogMessage() {
  1206. // Don't access errno directly because it may have been altered
  1207. // while streaming the message.
  1208. char buf[100];
  1209. posix_strerror_r(preserved_errno(), buf, sizeof(buf));
  1210. stream() << ": " << buf << " [" << preserved_errno() << "]";
  1211. }
  1212. void FlushLogFiles(LogSeverity min_severity) {
  1213. LogDestination::FlushLogFiles(min_severity);
  1214. }
  1215. void FlushLogFilesUnsafe(LogSeverity min_severity) {
  1216. LogDestination::FlushLogFilesUnsafe(min_severity);
  1217. }
  1218. void SetLogDestination(LogSeverity severity, const char* base_filename) {
  1219. LogDestination::SetLogDestination(severity, base_filename);
  1220. }
  1221. void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
  1222. LogDestination::SetLogSymlink(severity, symlink_b