blob: 1df1034ae58dd7960c5edda9c9d0173669c7d494 [file] [log] [blame]
Austin Schuh906616c2019-01-21 20:25:11 -08001// 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 <algorithm>
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070035#include <cassert>
Austin Schuh906616c2019-01-21 20:25:11 -080036#include <iomanip>
37#include <string>
38#ifdef HAVE_UNISTD_H
39# include <unistd.h> // For _exit.
40#endif
41#include <climits>
42#include <sys/types.h>
43#include <sys/stat.h>
44#ifdef HAVE_SYS_UTSNAME_H
45# include <sys/utsname.h> // For uname.
46#endif
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070047#include <ctime>
Austin Schuh906616c2019-01-21 20:25:11 -080048#include <fcntl.h>
49#include <cstdio>
50#include <iostream>
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070051#include <cstdarg>
52#include <cstdlib>
Austin Schuh906616c2019-01-21 20:25:11 -080053#ifdef HAVE_PWD_H
54# include <pwd.h>
55#endif
56#ifdef HAVE_SYSLOG_H
57# include <syslog.h>
58#endif
59#include <vector>
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070060#include <cerrno> // for errno
Austin Schuh906616c2019-01-21 20:25:11 -080061#include <sstream>
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070062#ifdef GLOG_OS_WINDOWS
63#include "windows/dirent.h"
64#else
65#include <dirent.h> // for automatic removal of old logs
66#endif
Austin Schuh906616c2019-01-21 20:25:11 -080067#include "base/commandlineflags.h" // to get the program name
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070068#include <glog/logging.h>
69#include <glog/raw_logging.h>
Austin Schuh906616c2019-01-21 20:25:11 -080070#include "base/googleinit.h"
71
72#ifdef HAVE_STACKTRACE
73# include "stacktrace.h"
74#endif
75
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070076#ifdef __ANDROID__
77#include <android/log.h>
78#endif
79
Austin Schuh906616c2019-01-21 20:25:11 -080080using std::string;
81using std::vector;
82using std::setw;
83using std::setfill;
84using std::hex;
85using std::dec;
86using std::min;
87using std::ostream;
88using std::ostringstream;
89
90using std::FILE;
91using std::fwrite;
92using std::fclose;
93using std::fflush;
94using std::fprintf;
95using std::perror;
96
97#ifdef __QNX__
98using std::fdopen;
99#endif
100
101#ifdef _WIN32
102#define fdopen _fdopen
103#endif
104
105// There is no thread annotation support.
106#define EXCLUSIVE_LOCKS_REQUIRED(mu)
107
108static bool BoolFromEnv(const char *varname, bool defval) {
109 const char* const valstr = getenv(varname);
110 if (!valstr) {
111 return defval;
112 }
113 return memchr("tTyY1\0", valstr[0], 6) != NULL;
114}
115
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700116GLOG_DEFINE_bool(timestamp_in_logfile_name,
117 BoolFromEnv("GOOGLE_TIMESTAMP_IN_LOGFILE_NAME", true),
118 "put a timestamp at the end of the log file name");
Austin Schuh906616c2019-01-21 20:25:11 -0800119GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
120 "log messages go to stderr instead of logfiles");
121GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
122 "log messages go to stderr in addition to logfiles");
123GLOG_DEFINE_bool(colorlogtostderr, false,
124 "color messages logged to stderr (if supported by terminal)");
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700125GLOG_DEFINE_bool(colorlogtostdout, false,
126 "color messages logged to stdout (if supported by terminal)");
127GLOG_DEFINE_bool(logtostdout, BoolFromEnv("GOOGLE_LOGTOSTDOUT", false),
128 "log messages go to stdout instead of logfiles");
129#ifdef GLOG_OS_LINUX
Austin Schuh906616c2019-01-21 20:25:11 -0800130GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
131 "Logs can grow very quickly and they are rarely read before they "
132 "need to be evicted from memory. Instead, drop them from memory "
133 "as soon as they are flushed to disk.");
134#endif
135
136// By default, errors (including fatal errors) get logged to stderr as
137// well as the file.
138//
139// The default is ERROR instead of FATAL so that users can see problems
140// when they run a program without having to look in another file.
141DEFINE_int32(stderrthreshold,
142 GOOGLE_NAMESPACE::GLOG_ERROR,
143 "log messages at or above this level are copied to stderr in "
144 "addition to logfiles. This flag obsoletes --alsologtostderr.");
145
146GLOG_DEFINE_string(alsologtoemail, "",
147 "log messages go to these email addresses "
148 "in addition to logfiles");
149GLOG_DEFINE_bool(log_prefix, true,
150 "Prepend the log prefix to the start of each log line");
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700151GLOG_DEFINE_bool(log_year_in_prefix, true,
152 "Include the year in the log prefix");
Austin Schuh906616c2019-01-21 20:25:11 -0800153GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
154 "actually get logged anywhere");
155GLOG_DEFINE_int32(logbuflevel, 0,
156 "Buffer log messages logged at this level or lower"
157 " (-1 means don't buffer; 0 means buffer INFO only;"
158 " ...)");
159GLOG_DEFINE_int32(logbufsecs, 30,
160 "Buffer log messages for at most this many seconds");
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700161
162GLOG_DEFINE_int32(logcleansecs, 60 * 5, // every 5 minutes
163 "Clean overdue logs every this many seconds");
164
Austin Schuh906616c2019-01-21 20:25:11 -0800165GLOG_DEFINE_int32(logemaillevel, 999,
166 "Email log messages logged at this level or higher"
167 " (0 means email all; 3 means email FATAL only;"
168 " ...)");
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700169GLOG_DEFINE_string(logmailer, "",
Austin Schuh906616c2019-01-21 20:25:11 -0800170 "Mailer used to send logging email");
171
172// Compute the default value for --log_dir
173static const char* DefaultLogDir() {
174 const char* env;
175 env = getenv("GOOGLE_LOG_DIR");
176 if (env != NULL && env[0] != '\0') {
177 return env;
178 }
179 env = getenv("TEST_TMPDIR");
180 if (env != NULL && env[0] != '\0') {
181 return env;
182 }
183 return "";
184}
185
186GLOG_DEFINE_int32(logfile_mode, 0664, "Log file mode/permissions.");
187
188GLOG_DEFINE_string(log_dir, DefaultLogDir(),
189 "If specified, logfiles are written into this directory instead "
190 "of the default logging directory.");
191GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
192 "files in this directory");
193
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700194GLOG_DEFINE_uint32(max_log_size, 1800,
195 "approx. maximum log file size (in MB). A value of 0 will "
196 "be silently overridden to 1.");
Austin Schuh906616c2019-01-21 20:25:11 -0800197
198GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
199 "Stop attempting to log to disk if the disk is full.");
200
201GLOG_DEFINE_string(log_backtrace_at, "",
202 "Emit a backtrace when logging at file:linenum.");
203
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700204GLOG_DEFINE_bool(log_utc_time, false,
205 "Use UTC time for logging.");
206
Austin Schuh906616c2019-01-21 20:25:11 -0800207// TODO(hamaji): consider windows
208#define PATH_SEPARATOR '/'
209
210#ifndef HAVE_PREAD
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700211#if defined(GLOG_OS_WINDOWS)
Austin Schuh906616c2019-01-21 20:25:11 -0800212#include <basetsd.h>
213#define ssize_t SSIZE_T
214#endif
215static ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
216 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
217 if (orig_offset == (off_t)-1)
218 return -1;
219 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
220 return -1;
221 ssize_t len = read(fd, buf, count);
222 if (len < 0)
223 return len;
224 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
225 return -1;
226 return len;
227}
228#endif // !HAVE_PREAD
229
230#ifndef HAVE_PWRITE
231static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) {
232 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
233 if (orig_offset == (off_t)-1)
234 return -1;
235 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
236 return -1;
237 ssize_t len = write(fd, buf, count);
238 if (len < 0)
239 return len;
240 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
241 return -1;
242 return len;
243}
244#endif // !HAVE_PWRITE
245
246static void GetHostName(string* hostname) {
247#if defined(HAVE_SYS_UTSNAME_H)
248 struct utsname buf;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700249 if (uname(&buf) < 0) {
Austin Schuh906616c2019-01-21 20:25:11 -0800250 // ensure null termination on failure
251 *buf.nodename = '\0';
252 }
253 *hostname = buf.nodename;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700254#elif defined(GLOG_OS_WINDOWS)
Austin Schuh906616c2019-01-21 20:25:11 -0800255 char buf[MAX_COMPUTERNAME_LENGTH + 1];
256 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
257 if (GetComputerNameA(buf, &len)) {
258 *hostname = buf;
259 } else {
260 hostname->clear();
261 }
262#else
263# warning There is no way to retrieve the host name.
264 *hostname = "(unknown)";
265#endif
266}
267
268// Returns true iff terminal supports using colors in output.
269static bool TerminalSupportsColor() {
270 bool term_supports_color = false;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700271#ifdef GLOG_OS_WINDOWS
Austin Schuh906616c2019-01-21 20:25:11 -0800272 // on Windows TERM variable is usually not set, but the console does
273 // support colors.
274 term_supports_color = true;
275#else
276 // On non-Windows platforms, we rely on the TERM variable.
277 const char* const term = getenv("TERM");
278 if (term != NULL && term[0] != '\0') {
279 term_supports_color =
280 !strcmp(term, "xterm") ||
281 !strcmp(term, "xterm-color") ||
282 !strcmp(term, "xterm-256color") ||
283 !strcmp(term, "screen-256color") ||
284 !strcmp(term, "konsole") ||
285 !strcmp(term, "konsole-16color") ||
286 !strcmp(term, "konsole-256color") ||
287 !strcmp(term, "screen") ||
288 !strcmp(term, "linux") ||
289 !strcmp(term, "cygwin");
290 }
291#endif
292 return term_supports_color;
293}
294
295_START_GOOGLE_NAMESPACE_
296
297enum GLogColor {
298 COLOR_DEFAULT,
299 COLOR_RED,
300 COLOR_GREEN,
301 COLOR_YELLOW
302};
303
304static GLogColor SeverityToColor(LogSeverity severity) {
305 assert(severity >= 0 && severity < NUM_SEVERITIES);
306 GLogColor color = COLOR_DEFAULT;
307 switch (severity) {
308 case GLOG_INFO:
309 color = COLOR_DEFAULT;
310 break;
311 case GLOG_WARNING:
312 color = COLOR_YELLOW;
313 break;
314 case GLOG_ERROR:
315 case GLOG_FATAL:
316 color = COLOR_RED;
317 break;
318 default:
319 // should never get here.
320 assert(false);
321 }
322 return color;
323}
324
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700325#ifdef GLOG_OS_WINDOWS
Austin Schuh906616c2019-01-21 20:25:11 -0800326
327// Returns the character attribute for the given color.
328static WORD GetColorAttribute(GLogColor color) {
329 switch (color) {
330 case COLOR_RED: return FOREGROUND_RED;
331 case COLOR_GREEN: return FOREGROUND_GREEN;
332 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
333 default: return 0;
334 }
335}
336
337#else
338
339// Returns the ANSI color code for the given color.
340static const char* GetAnsiColorCode(GLogColor color) {
341 switch (color) {
342 case COLOR_RED: return "1";
343 case COLOR_GREEN: return "2";
344 case COLOR_YELLOW: return "3";
345 case COLOR_DEFAULT: return "";
346 };
347 return NULL; // stop warning about return type.
348}
349
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700350#endif // GLOG_OS_WINDOWS
Austin Schuh906616c2019-01-21 20:25:11 -0800351
352// Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700353static uint32 MaxLogSize() {
354 return (FLAGS_max_log_size > 0 && FLAGS_max_log_size < 4096
355 ? FLAGS_max_log_size
356 : 1);
Austin Schuh906616c2019-01-21 20:25:11 -0800357}
358
359// An arbitrary limit on the length of a single log message. This
360// is so that streaming can be done more efficiently.
361const size_t LogMessage::kMaxLogMessageLen = 30000;
362
363struct LogMessage::LogMessageData {
364 LogMessageData();
365
366 int preserved_errno_; // preserved errno
367 // Buffer space; contains complete message text.
368 char message_text_[LogMessage::kMaxLogMessageLen+1];
369 LogStream stream_;
370 char severity_; // What level is this LogMessage logged at?
371 int line_; // line number where logging call is.
372 void (LogMessage::*send_method_)(); // Call this in destructor to send
373 union { // At most one of these is used: union to keep the size low.
374 LogSink* sink_; // NULL or sink to send message to
375 std::vector<std::string>* outvec_; // NULL or vector to push message onto
376 std::string* message_; // NULL or string to write message into
377 };
Austin Schuh906616c2019-01-21 20:25:11 -0800378 size_t num_prefix_chars_; // # of chars of prefix in this message
379 size_t num_chars_to_log_; // # of chars of msg to send to log
380 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
381 const char* basename_; // basename of file that called LOG
382 const char* fullname_; // fullname of file that called LOG
383 bool has_been_flushed_; // false => data has not been flushed
384 bool first_fatal_; // true => this was first fatal msg
385
386 private:
387 LogMessageData(const LogMessageData&);
388 void operator=(const LogMessageData&);
389};
390
391// A mutex that allows only one thread to log at a time, to keep things from
392// getting jumbled. Some other very uncommon logging operations (like
393// changing the destination file for log messages of a given severity) also
394// lock this mutex. Please be sure that anybody who might possibly need to
395// lock it does so.
396static Mutex log_mutex;
397
398// Number of messages sent at each severity. Under log_mutex.
399int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
400
401// Globally disable log writing (if disk is full)
402static bool stop_writing = false;
403
404const char*const LogSeverityNames[NUM_SEVERITIES] = {
405 "INFO", "WARNING", "ERROR", "FATAL"
406};
407
408// Has the user called SetExitOnDFatal(true)?
409static bool exit_on_dfatal = true;
410
411const char* GetLogSeverityName(LogSeverity severity) {
412 return LogSeverityNames[severity];
413}
414
415static bool SendEmailInternal(const char*dest, const char *subject,
416 const char*body, bool use_logging);
417
418base::Logger::~Logger() {
419}
420
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700421#ifdef GLOG_CUSTOM_PREFIX_SUPPORT
422namespace {
423 // Optional user-configured callback to print custom prefixes.
424 CustomPrefixCallback custom_prefix_callback = NULL;
425 // User-provided data to pass to the callback:
426 void* custom_prefix_callback_data = NULL;
427}
428#endif
429
Austin Schuh906616c2019-01-21 20:25:11 -0800430namespace {
431
432// Encapsulates all file-system related state
433class LogFileObject : public base::Logger {
434 public:
435 LogFileObject(LogSeverity severity, const char* base_filename);
436 ~LogFileObject();
437
438 virtual void Write(bool force_flush, // Should we force a flush here?
439 time_t timestamp, // Timestamp for this entry
440 const char* message,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700441 size_t message_len);
Austin Schuh906616c2019-01-21 20:25:11 -0800442
443 // Configuration options
444 void SetBasename(const char* basename);
445 void SetExtension(const char* ext);
446 void SetSymlinkBasename(const char* symlink_basename);
447
448 // Normal flushing routine
449 virtual void Flush();
450
451 // It is the actual file length for the system loggers,
452 // i.e., INFO, ERROR, etc.
453 virtual uint32 LogSize() {
454 MutexLock l(&lock_);
455 return file_length_;
456 }
457
458 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
459 // can avoid grabbing a lock. Usually Flush() calls it after
460 // acquiring lock_.
461 void FlushUnlocked();
462
463 private:
464 static const uint32 kRolloverAttemptFrequency = 0x20;
465
466 Mutex lock_;
467 bool base_filename_selected_;
468 string base_filename_;
469 string symlink_basename_;
470 string filename_extension_; // option users can specify (eg to add port#)
471 FILE* file_;
472 LogSeverity severity_;
473 uint32 bytes_since_flush_;
474 uint32 dropped_mem_length_;
475 uint32 file_length_;
476 unsigned int rollover_attempt_;
477 int64 next_flush_time_; // cycle count at which to flush log
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700478 WallTime start_time_;
Austin Schuh906616c2019-01-21 20:25:11 -0800479
480 // Actually create a logfile using the value of base_filename_ and the
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700481 // optional argument time_pid_string
Austin Schuh906616c2019-01-21 20:25:11 -0800482 // REQUIRES: lock_ is held
483 bool CreateLogfile(const string& time_pid_string);
484};
485
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700486// Encapsulate all log cleaner related states
487class LogCleaner {
488 public:
489 LogCleaner();
490
491 // Setting overdue_days to 0 days will delete all logs.
492 void Enable(unsigned int overdue_days);
493 void Disable();
494
495 // update next_cleanup_time_
496 void UpdateCleanUpTime();
497
498 void Run(bool base_filename_selected,
499 const string& base_filename,
500 const string& filename_extension);
501
502 bool enabled() const { return enabled_; }
503
504 private:
505 vector<string> GetOverdueLogNames(string log_directory, unsigned int days,
506 const string& base_filename,
507 const string& filename_extension) const;
508
509 bool IsLogFromCurrentProject(const string& filepath,
510 const string& base_filename,
511 const string& filename_extension) const;
512
513 bool IsLogLastModifiedOver(const string& filepath, unsigned int days) const;
514
515 bool enabled_;
516 unsigned int overdue_days_;
517 int64 next_cleanup_time_; // cycle count at which to clean overdue log
518};
519
520LogCleaner log_cleaner;
521
Austin Schuh906616c2019-01-21 20:25:11 -0800522} // namespace
523
524class LogDestination {
525 public:
526 friend class LogMessage;
527 friend void ReprintFatalMessage();
528 friend base::Logger* base::GetLogger(LogSeverity);
529 friend void base::SetLogger(LogSeverity, base::Logger*);
530
531 // These methods are just forwarded to by their global versions.
532 static void SetLogDestination(LogSeverity severity,
533 const char* base_filename);
534 static void SetLogSymlink(LogSeverity severity,
535 const char* symlink_basename);
536 static void AddLogSink(LogSink *destination);
537 static void RemoveLogSink(LogSink *destination);
538 static void SetLogFilenameExtension(const char* filename_extension);
539 static void SetStderrLogging(LogSeverity min_severity);
540 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
541 static void LogToStderr();
542 // Flush all log files that are at least at the given severity level
543 static void FlushLogFiles(int min_severity);
544 static void FlushLogFilesUnsafe(int min_severity);
545
546 // we set the maximum size of our packet to be 1400, the logic being
547 // to prevent fragmentation.
548 // Really this number is arbitrary.
549 static const int kNetworkBytes = 1400;
550
551 static const string& hostname();
552 static const bool& terminal_supports_color() {
553 return terminal_supports_color_;
554 }
555
556 static void DeleteLogDestinations();
557
558 private:
559 LogDestination(LogSeverity severity, const char* base_filename);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700560 ~LogDestination();
Austin Schuh906616c2019-01-21 20:25:11 -0800561
562 // Take a log message of a particular severity and log it to stderr
563 // iff it's of a high enough severity to deserve it.
564 static void MaybeLogToStderr(LogSeverity severity, const char* message,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700565 size_t message_len, size_t prefix_len);
Austin Schuh906616c2019-01-21 20:25:11 -0800566
567 // Take a log message of a particular severity and log it to email
568 // iff it's of a high enough severity to deserve it.
569 static void MaybeLogToEmail(LogSeverity severity, const char* message,
570 size_t len);
571 // Take a log message of a particular severity and log it to a file
572 // iff the base filename is not "" (which means "don't log to me")
573 static void MaybeLogToLogfile(LogSeverity severity,
574 time_t timestamp,
575 const char* message, size_t len);
576 // Take a log message of a particular severity and log it to the file
577 // for that severity and also for all files with severity less than
578 // this severity.
579 static void LogToAllLogfiles(LogSeverity severity,
580 time_t timestamp,
581 const char* message, size_t len);
582
583 // Send logging info to all registered sinks.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700584 static void LogToSinks(LogSeverity severity, const char* full_filename,
585 const char* base_filename, int line,
586 const LogMessageTime& logmsgtime, const char* message,
Austin Schuh906616c2019-01-21 20:25:11 -0800587 size_t message_len);
588
589 // Wait for all registered sinks via WaitTillSent
590 // including the optional one in "data".
591 static void WaitForSinks(LogMessage::LogMessageData* data);
592
593 static LogDestination* log_destination(LogSeverity severity);
594
595 LogFileObject fileobject_;
596 base::Logger* logger_; // Either &fileobject_, or wrapper around it
597
598 static LogDestination* log_destinations_[NUM_SEVERITIES];
599 static LogSeverity email_logging_severity_;
600 static string addresses_;
601 static string hostname_;
602 static bool terminal_supports_color_;
603
604 // arbitrary global logging destinations.
605 static vector<LogSink*>* sinks_;
606
607 // Protects the vector sinks_,
608 // but not the LogSink objects its elements reference.
609 static Mutex sink_mutex_;
610
611 // Disallow
612 LogDestination(const LogDestination&);
613 LogDestination& operator=(const LogDestination&);
614};
615
616// Errors do not get logged to email by default.
617LogSeverity LogDestination::email_logging_severity_ = 99999;
618
619string LogDestination::addresses_;
620string LogDestination::hostname_;
621
622vector<LogSink*>* LogDestination::sinks_ = NULL;
623Mutex LogDestination::sink_mutex_;
624bool LogDestination::terminal_supports_color_ = TerminalSupportsColor();
625
626/* static */
627const string& LogDestination::hostname() {
628 if (hostname_.empty()) {
629 GetHostName(&hostname_);
630 if (hostname_.empty()) {
631 hostname_ = "(unknown)";
632 }
633 }
634 return hostname_;
635}
636
637LogDestination::LogDestination(LogSeverity severity,
638 const char* base_filename)
639 : fileobject_(severity, base_filename),
640 logger_(&fileobject_) {
641}
642
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700643LogDestination::~LogDestination() {
644 if (logger_ && logger_ != &fileobject_) {
645 // Delete user-specified logger set via SetLogger().
646 delete logger_;
647 }
648}
649
Austin Schuh906616c2019-01-21 20:25:11 -0800650inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
651 // assume we have the log_mutex or we simply don't care
652 // about it
653 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
654 LogDestination* log = log_destinations_[i];
655 if (log != NULL) {
656 // Flush the base fileobject_ logger directly instead of going
657 // through any wrappers to reduce chance of deadlock.
658 log->fileobject_.FlushUnlocked();
659 }
660 }
661}
662
663inline void LogDestination::FlushLogFiles(int min_severity) {
664 // Prevent any subtle race conditions by wrapping a mutex lock around
665 // all this stuff.
666 MutexLock l(&log_mutex);
667 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
668 LogDestination* log = log_destination(i);
669 if (log != NULL) {
670 log->logger_->Flush();
671 }
672 }
673}
674
675inline void LogDestination::SetLogDestination(LogSeverity severity,
676 const char* base_filename) {
677 assert(severity >= 0 && severity < NUM_SEVERITIES);
678 // Prevent any subtle race conditions by wrapping a mutex lock around
679 // all this stuff.
680 MutexLock l(&log_mutex);
681 log_destination(severity)->fileobject_.SetBasename(base_filename);
682}
683
684inline void LogDestination::SetLogSymlink(LogSeverity severity,
685 const char* symlink_basename) {
686 CHECK_GE(severity, 0);
687 CHECK_LT(severity, NUM_SEVERITIES);
688 MutexLock l(&log_mutex);
689 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
690}
691
692inline void LogDestination::AddLogSink(LogSink *destination) {
693 // Prevent any subtle race conditions by wrapping a mutex lock around
694 // all this stuff.
695 MutexLock l(&sink_mutex_);
696 if (!sinks_) sinks_ = new vector<LogSink*>;
697 sinks_->push_back(destination);
698}
699
700inline void LogDestination::RemoveLogSink(LogSink *destination) {
701 // Prevent any subtle race conditions by wrapping a mutex lock around
702 // all this stuff.
703 MutexLock l(&sink_mutex_);
704 // This doesn't keep the sinks in order, but who cares?
705 if (sinks_) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700706 sinks_->erase(std::remove(sinks_->begin(), sinks_->end(), destination), sinks_->end());
Austin Schuh906616c2019-01-21 20:25:11 -0800707 }
708}
709
710inline void LogDestination::SetLogFilenameExtension(const char* ext) {
711 // Prevent any subtle race conditions by wrapping a mutex lock around
712 // all this stuff.
713 MutexLock l(&log_mutex);
714 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
715 log_destination(severity)->fileobject_.SetExtension(ext);
716 }
717}
718
719inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
720 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
721 // Prevent any subtle race conditions by wrapping a mutex lock around
722 // all this stuff.
723 MutexLock l(&log_mutex);
724 FLAGS_stderrthreshold = min_severity;
725}
726
727inline void LogDestination::LogToStderr() {
728 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
729 // SetLogDestination already do the locking!
730 SetStderrLogging(0); // thus everything is "also" logged to stderr
731 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
732 SetLogDestination(i, ""); // "" turns off logging to a logfile
733 }
734}
735
736inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
737 const char* addresses) {
738 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
739 // Prevent any subtle race conditions by wrapping a mutex lock around
740 // all this stuff.
741 MutexLock l(&log_mutex);
742 LogDestination::email_logging_severity_ = min_severity;
743 LogDestination::addresses_ = addresses;
744}
745
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700746static void ColoredWriteToStderrOrStdout(FILE* output, LogSeverity severity,
747 const char* message, size_t len) {
748 bool is_stdout = (output == stdout);
749 const GLogColor color = (LogDestination::terminal_supports_color() &&
750 ((!is_stdout && FLAGS_colorlogtostderr) ||
751 (is_stdout && FLAGS_colorlogtostdout)))
752 ? SeverityToColor(severity)
753 : COLOR_DEFAULT;
Austin Schuh906616c2019-01-21 20:25:11 -0800754
755 // Avoid using cerr from this module since we may get called during
756 // exit code, and cerr may be partially or fully destroyed by then.
757 if (COLOR_DEFAULT == color) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700758 fwrite(message, len, 1, output);
Austin Schuh906616c2019-01-21 20:25:11 -0800759 return;
760 }
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700761#ifdef GLOG_OS_WINDOWS
762 const HANDLE output_handle =
763 GetStdHandle(is_stdout ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
Austin Schuh906616c2019-01-21 20:25:11 -0800764
765 // Gets the current text color.
766 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700767 GetConsoleScreenBufferInfo(output_handle, &buffer_info);
Austin Schuh906616c2019-01-21 20:25:11 -0800768 const WORD old_color_attrs = buffer_info.wAttributes;
769
770 // We need to flush the stream buffers into the console before each
771 // SetConsoleTextAttribute call lest it affect the text that is already
772 // printed but has not yet reached the console.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700773 fflush(output);
774 SetConsoleTextAttribute(output_handle,
Austin Schuh906616c2019-01-21 20:25:11 -0800775 GetColorAttribute(color) | FOREGROUND_INTENSITY);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700776 fwrite(message, len, 1, output);
777 fflush(output);
Austin Schuh906616c2019-01-21 20:25:11 -0800778 // Restores the text color.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700779 SetConsoleTextAttribute(output_handle, old_color_attrs);
Austin Schuh906616c2019-01-21 20:25:11 -0800780#else
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700781 fprintf(output, "\033[0;3%sm", GetAnsiColorCode(color));
782 fwrite(message, len, 1, output);
783 fprintf(output, "\033[m"); // Resets the terminal to default.
784#endif // GLOG_OS_WINDOWS
785}
786
787static void ColoredWriteToStdout(LogSeverity severity, const char* message,
788 size_t len) {
789 FILE* output = stdout;
790 // We also need to send logs to the stderr when the severity is
791 // higher or equal to the stderr threshold.
792 if (severity >= FLAGS_stderrthreshold) {
793 output = stderr;
794 }
795 ColoredWriteToStderrOrStdout(output, severity, message, len);
796}
797
798static void ColoredWriteToStderr(LogSeverity severity, const char* message,
799 size_t len) {
800 ColoredWriteToStderrOrStdout(stderr, severity, message, len);
Austin Schuh906616c2019-01-21 20:25:11 -0800801}
802
803static void WriteToStderr(const char* message, size_t len) {
804 // Avoid using cerr from this module since we may get called during
805 // exit code, and cerr may be partially or fully destroyed by then.
806 fwrite(message, len, 1, stderr);
807}
808
809inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700810 const char* message, size_t message_len, size_t prefix_len) {
Austin Schuh906616c2019-01-21 20:25:11 -0800811 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700812 ColoredWriteToStderr(severity, message, message_len);
813#ifdef GLOG_OS_WINDOWS
814 (void) prefix_len;
Austin Schuh906616c2019-01-21 20:25:11 -0800815 // On Windows, also output to the debugger
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700816 ::OutputDebugStringA(message);
817#elif defined(__ANDROID__)
818 // On Android, also output to logcat
819 const int android_log_levels[NUM_SEVERITIES] = {
820 ANDROID_LOG_INFO,
821 ANDROID_LOG_WARN,
822 ANDROID_LOG_ERROR,
823 ANDROID_LOG_FATAL,
824 };
825 __android_log_write(android_log_levels[severity],
826 glog_internal_namespace_::ProgramInvocationShortName(),
827 message + prefix_len);
828#else
829 (void) prefix_len;
Austin Schuh906616c2019-01-21 20:25:11 -0800830#endif
831 }
832}
833
834
835inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
836 const char* message, size_t len) {
837 if (severity >= email_logging_severity_ ||
838 severity >= FLAGS_logemaillevel) {
839 string to(FLAGS_alsologtoemail);
840 if (!addresses_.empty()) {
841 if (!to.empty()) {
842 to += ",";
843 }
844 to += addresses_;
845 }
846 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
847 glog_internal_namespace_::ProgramInvocationShortName());
848 string body(hostname());
849 body += "\n\n";
850 body.append(message, len);
851
852 // should NOT use SendEmail(). The caller of this function holds the
853 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
854 // acquire the log_mutex object. Use SendEmailInternal() and set
855 // use_logging to false.
856 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
857 }
858}
859
860
861inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
862 time_t timestamp,
863 const char* message,
864 size_t len) {
865 const bool should_flush = severity > FLAGS_logbuflevel;
866 LogDestination* destination = log_destination(severity);
867 destination->logger_->Write(should_flush, timestamp, message, len);
868}
869
870inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
871 time_t timestamp,
872 const char* message,
873 size_t len) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700874 if (FLAGS_logtostdout) { // global flag: never log to file
875 ColoredWriteToStdout(severity, message, len);
876 } else if (FLAGS_logtostderr) { // global flag: never log to file
Austin Schuh906616c2019-01-21 20:25:11 -0800877 ColoredWriteToStderr(severity, message, len);
878 } else {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700879 for (int i = severity; i >= 0; --i) {
Austin Schuh906616c2019-01-21 20:25:11 -0800880 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700881 }
Austin Schuh906616c2019-01-21 20:25:11 -0800882 }
883}
884
885inline void LogDestination::LogToSinks(LogSeverity severity,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700886 const char* full_filename,
887 const char* base_filename, int line,
888 const LogMessageTime& logmsgtime,
Austin Schuh906616c2019-01-21 20:25:11 -0800889 const char* message,
890 size_t message_len) {
891 ReaderMutexLock l(&sink_mutex_);
892 if (sinks_) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700893 for (size_t i = sinks_->size(); i-- > 0; ) {
Austin Schuh906616c2019-01-21 20:25:11 -0800894 (*sinks_)[i]->send(severity, full_filename, base_filename,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700895 line, logmsgtime, message, message_len);
Austin Schuh906616c2019-01-21 20:25:11 -0800896 }
897 }
898}
899
900inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
901 ReaderMutexLock l(&sink_mutex_);
902 if (sinks_) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700903 for (size_t i = sinks_->size(); i-- > 0; ) {
Austin Schuh906616c2019-01-21 20:25:11 -0800904 (*sinks_)[i]->WaitTillSent();
905 }
906 }
907 const bool send_to_sink =
908 (data->send_method_ == &LogMessage::SendToSink) ||
909 (data->send_method_ == &LogMessage::SendToSinkAndLog);
910 if (send_to_sink && data->sink_ != NULL) {
911 data->sink_->WaitTillSent();
912 }
913}
914
915LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
916
917inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
918 assert(severity >=0 && severity < NUM_SEVERITIES);
919 if (!log_destinations_[severity]) {
920 log_destinations_[severity] = new LogDestination(severity, NULL);
921 }
922 return log_destinations_[severity];
923}
924
925void LogDestination::DeleteLogDestinations() {
926 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
927 delete log_destinations_[severity];
928 log_destinations_[severity] = NULL;
929 }
930 MutexLock l(&sink_mutex_);
931 delete sinks_;
932 sinks_ = NULL;
933}
934
935namespace {
936
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700937std::string g_application_fingerprint;
938
939} // namespace
940
941void SetApplicationFingerprint(const std::string& fingerprint) {
942 g_application_fingerprint = fingerprint;
943}
944
945namespace {
946
947// Directory delimiter; Windows supports both forward slashes and backslashes
948#ifdef GLOG_OS_WINDOWS
949const char possible_dir_delim[] = {'\\', '/'};
950#else
951const char possible_dir_delim[] = {'/'};
952#endif
953
954string PrettyDuration(int secs) {
955 std::stringstream result;
956 int mins = secs / 60;
957 int hours = mins / 60;
958 mins = mins % 60;
959 secs = secs % 60;
960 result.fill('0');
961 result << hours << ':' << setw(2) << mins << ':' << setw(2) << secs;
962 return result.str();
963}
964
965
Austin Schuh906616c2019-01-21 20:25:11 -0800966LogFileObject::LogFileObject(LogSeverity severity,
967 const char* base_filename)
968 : base_filename_selected_(base_filename != NULL),
969 base_filename_((base_filename != NULL) ? base_filename : ""),
970 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
971 filename_extension_(),
972 file_(NULL),
973 severity_(severity),
974 bytes_since_flush_(0),
975 dropped_mem_length_(0),
976 file_length_(0),
977 rollover_attempt_(kRolloverAttemptFrequency-1),
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700978 next_flush_time_(0),
979 start_time_(WallTime_Now()) {
Austin Schuh906616c2019-01-21 20:25:11 -0800980 assert(severity >= 0);
981 assert(severity < NUM_SEVERITIES);
982}
983
984LogFileObject::~LogFileObject() {
985 MutexLock l(&lock_);
986 if (file_ != NULL) {
987 fclose(file_);
988 file_ = NULL;
989 }
990}
991
992void LogFileObject::SetBasename(const char* basename) {
993 MutexLock l(&lock_);
994 base_filename_selected_ = true;
995 if (base_filename_ != basename) {
996 // Get rid of old log file since we are changing names
997 if (file_ != NULL) {
998 fclose(file_);
999 file_ = NULL;
1000 rollover_attempt_ = kRolloverAttemptFrequency-1;
1001 }
1002 base_filename_ = basename;
1003 }
1004}
1005
1006void LogFileObject::SetExtension(const char* ext) {
1007 MutexLock l(&lock_);
1008 if (filename_extension_ != ext) {
1009 // Get rid of old log file since we are changing names
1010 if (file_ != NULL) {
1011 fclose(file_);
1012 file_ = NULL;
1013 rollover_attempt_ = kRolloverAttemptFrequency-1;
1014 }
1015 filename_extension_ = ext;
1016 }
1017}
1018
1019void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
1020 MutexLock l(&lock_);
1021 symlink_basename_ = symlink_basename;
1022}
1023
1024void LogFileObject::Flush() {
1025 MutexLock l(&lock_);
1026 FlushUnlocked();
1027}
1028
1029void LogFileObject::FlushUnlocked(){
1030 if (file_ != NULL) {
1031 fflush(file_);
1032 bytes_since_flush_ = 0;
1033 }
1034 // Figure out when we are due for another flush.
1035 const int64 next = (FLAGS_logbufsecs
1036 * static_cast<int64>(1000000)); // in usec
1037 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
1038}
1039
1040bool LogFileObject::CreateLogfile(const string& time_pid_string) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001041 string string_filename = base_filename_;
1042 if (FLAGS_timestamp_in_logfile_name) {
1043 string_filename += time_pid_string;
1044 }
1045 string_filename += filename_extension_;
Austin Schuh906616c2019-01-21 20:25:11 -08001046 const char* filename = string_filename.c_str();
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001047 //only write to files, create if non-existant.
1048 int flags = O_WRONLY | O_CREAT;
1049 if (FLAGS_timestamp_in_logfile_name) {
1050 //demand that the file is unique for our timestamp (fail if it exists).
1051 flags = flags | O_EXCL;
1052 }
1053 int fd = open(filename, flags, static_cast<mode_t>(FLAGS_logfile_mode));
Austin Schuh906616c2019-01-21 20:25:11 -08001054 if (fd == -1) return false;
1055#ifdef HAVE_FCNTL
1056 // Mark the file close-on-exec. We don't really care if this fails
1057 fcntl(fd, F_SETFD, FD_CLOEXEC);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001058
1059 // Mark the file as exclusive write access to avoid two clients logging to the
1060 // same file. This applies particularly when !FLAGS_timestamp_in_logfile_name
1061 // (otherwise open would fail because the O_EXCL flag on similar filename).
1062 // locks are released on unlock or close() automatically, only after log is
1063 // released.
1064 // This will work after a fork as it is not inherited (not stored in the fd).
1065 // Lock will not be lost because the file is opened with exclusive lock (write)
1066 // and we will never read from it inside the process.
1067 // TODO windows implementation of this (as flock is not available on mingw).
1068 static struct flock w_lock;
1069
1070 w_lock.l_type = F_WRLCK;
1071 w_lock.l_start = 0;
1072 w_lock.l_whence = SEEK_SET;
1073 w_lock.l_len = 0;
1074
1075 int wlock_ret = fcntl(fd, F_SETLK, &w_lock);
1076 if (wlock_ret == -1) {
1077 close(fd); //as we are failing already, do not check errors here
1078 return false;
1079 }
Austin Schuh906616c2019-01-21 20:25:11 -08001080#endif
1081
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001082 //fdopen in append mode so if the file exists it will fseek to the end
Austin Schuh906616c2019-01-21 20:25:11 -08001083 file_ = fdopen(fd, "a"); // Make a FILE*.
1084 if (file_ == NULL) { // Man, we're screwed!
1085 close(fd);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001086 if (FLAGS_timestamp_in_logfile_name) {
1087 unlink(filename); // Erase the half-baked evidence: an unusable log file, only if we just created it.
1088 }
Austin Schuh906616c2019-01-21 20:25:11 -08001089 return false;
1090 }
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001091#ifdef GLOG_OS_WINDOWS
1092 // https://github.com/golang/go/issues/27638 - make sure we seek to the end to append
1093 // empirically replicated with wine over mingw build
1094 if (!FLAGS_timestamp_in_logfile_name) {
1095 if (fseek(file_, 0, SEEK_END) != 0) {
1096 return false;
1097 }
1098 }
1099#endif
Austin Schuh906616c2019-01-21 20:25:11 -08001100 // We try to create a symlink called <program_name>.<severity>,
1101 // which is easier to use. (Every time we create a new logfile,
1102 // we destroy the old symlink and create a new one, so it always
1103 // points to the latest logfile.) If it fails, we're sad but it's
1104 // no error.
1105 if (!symlink_basename_.empty()) {
1106 // take directory from filename
1107 const char* slash = strrchr(filename, PATH_SEPARATOR);
1108 const string linkname =
1109 symlink_basename_ + '.' + LogSeverityNames[severity_];
1110 string linkpath;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001111 if ( slash ) linkpath = string(filename, static_cast<size_t>(slash-filename+1)); // get dirname
Austin Schuh906616c2019-01-21 20:25:11 -08001112 linkpath += linkname;
1113 unlink(linkpath.c_str()); // delete old one if it exists
1114
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001115#if defined(GLOG_OS_WINDOWS)
Austin Schuh906616c2019-01-21 20:25:11 -08001116 // TODO(hamaji): Create lnk file on Windows?
1117#elif defined(HAVE_UNISTD_H)
1118 // We must have unistd.h.
1119 // Make the symlink be relative (in the same dir) so that if the
1120 // entire log directory gets relocated the link is still valid.
1121 const char *linkdest = slash ? (slash + 1) : filename;
1122 if (symlink(linkdest, linkpath.c_str()) != 0) {
1123 // silently ignore failures
1124 }
1125
1126 // Make an additional link to the log file in a place specified by
1127 // FLAGS_log_link, if indicated
1128 if (!FLAGS_log_link.empty()) {
1129 linkpath = FLAGS_log_link + "/" + linkname;
1130 unlink(linkpath.c_str()); // delete old one if it exists
1131 if (symlink(filename, linkpath.c_str()) != 0) {
1132 // silently ignore failures
1133 }
1134 }
1135#endif
1136 }
1137
1138 return true; // Everything worked
1139}
1140
1141void LogFileObject::Write(bool force_flush,
1142 time_t timestamp,
1143 const char* message,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001144 size_t message_len) {
Austin Schuh906616c2019-01-21 20:25:11 -08001145 MutexLock l(&lock_);
1146
1147 // We don't log if the base_name_ is "" (which means "don't write")
1148 if (base_filename_selected_ && base_filename_.empty()) {
1149 return;
1150 }
1151
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001152 if (file_length_ >> 20U >= MaxLogSize() || PidHasChanged()) {
Austin Schuh906616c2019-01-21 20:25:11 -08001153 if (file_ != NULL) fclose(file_);
1154 file_ = NULL;
1155 file_length_ = bytes_since_flush_ = dropped_mem_length_ = 0;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001156 rollover_attempt_ = kRolloverAttemptFrequency - 1;
Austin Schuh906616c2019-01-21 20:25:11 -08001157 }
1158
1159 // If there's no destination file, make one before outputting
1160 if (file_ == NULL) {
1161 // Try to rollover the log file every 32 log messages. The only time
1162 // this could matter would be when we have trouble creating the log
1163 // file. If that happens, we'll lose lots of log messages, of course!
1164 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
1165 rollover_attempt_ = 0;
1166
1167 struct ::tm tm_time;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001168 if (FLAGS_log_utc_time) {
1169 gmtime_r(&timestamp, &tm_time);
1170 } else {
1171 localtime_r(&timestamp, &tm_time);
1172 }
Austin Schuh906616c2019-01-21 20:25:11 -08001173
1174 // The logfile's filename will have the date/time & pid in it
1175 ostringstream time_pid_stream;
1176 time_pid_stream.fill('0');
1177 time_pid_stream << 1900+tm_time.tm_year
1178 << setw(2) << 1+tm_time.tm_mon
1179 << setw(2) << tm_time.tm_mday
1180 << '-'
1181 << setw(2) << tm_time.tm_hour
1182 << setw(2) << tm_time.tm_min
1183 << setw(2) << tm_time.tm_sec
1184 << '.'
1185 << GetMainThreadPid();
1186 const string& time_pid_string = time_pid_stream.str();
1187
1188 if (base_filename_selected_) {
1189 if (!CreateLogfile(time_pid_string)) {
1190 perror("Could not create log file");
1191 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
1192 time_pid_string.c_str());
1193 return;
1194 }
1195 } else {
1196 // If no base filename for logs of this severity has been set, use a
1197 // default base filename of
1198 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
1199 // logfiles will have names like
1200 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
1201 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
1202 // and 4354 is the pid of the logging process. The date & time reflect
1203 // when the file was created for output.
1204 //
1205 // Where does the file get put? Successively try the directories
1206 // "/tmp", and "."
1207 string stripped_filename(
1208 glog_internal_namespace_::ProgramInvocationShortName());
1209 string hostname;
1210 GetHostName(&hostname);
1211
1212 string uidname = MyUserName();
1213 // We should not call CHECK() here because this function can be
1214 // called after holding on to log_mutex. We don't want to
1215 // attempt to hold on to the same mutex, and get into a
1216 // deadlock. Simply use a name like invalid-user.
1217 if (uidname.empty()) uidname = "invalid-user";
1218
1219 stripped_filename = stripped_filename+'.'+hostname+'.'
1220 +uidname+".log."
1221 +LogSeverityNames[severity_]+'.';
1222 // We're going to (potentially) try to put logs in several different dirs
1223 const vector<string> & log_dirs = GetLoggingDirectories();
1224
1225 // Go through the list of dirs, and try to create the log file in each
1226 // until we succeed or run out of options
1227 bool success = false;
1228 for (vector<string>::const_iterator dir = log_dirs.begin();
1229 dir != log_dirs.end();
1230 ++dir) {
1231 base_filename_ = *dir + "/" + stripped_filename;
1232 if ( CreateLogfile(time_pid_string) ) {
1233 success = true;
1234 break;
1235 }
1236 }
1237 // If we never succeeded, we have to give up
1238 if ( success == false ) {
1239 perror("Could not create logging file");
1240 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
1241 time_pid_string.c_str());
1242 return;
1243 }
1244 }
1245
1246 // Write a header message into the log file
1247 ostringstream file_header_stream;
1248 file_header_stream.fill('0');
1249 file_header_stream << "Log file created at: "
1250 << 1900+tm_time.tm_year << '/'
1251 << setw(2) << 1+tm_time.tm_mon << '/'
1252 << setw(2) << tm_time.tm_mday
1253 << ' '
1254 << setw(2) << tm_time.tm_hour << ':'
1255 << setw(2) << tm_time.tm_min << ':'
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001256 << setw(2) << tm_time.tm_sec << (FLAGS_log_utc_time ? " UTC\n" : "\n")
Austin Schuh906616c2019-01-21 20:25:11 -08001257 << "Running on machine: "
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001258 << LogDestination::hostname() << '\n';
1259
1260 if(!g_application_fingerprint.empty()) {
1261 file_header_stream << "Application fingerprint: " << g_application_fingerprint << '\n';
1262 }
1263 const char* const date_time_format = FLAGS_log_year_in_prefix
1264 ? "yyyymmdd hh:mm:ss.uuuuuu"
1265 : "mmdd hh:mm:ss.uuuuuu";
1266 file_header_stream << "Running duration (h:mm:ss): "
1267 << PrettyDuration(static_cast<int>(WallTime_Now() - start_time_)) << '\n'
1268 << "Log line format: [IWEF]" << date_time_format << " "
Austin Schuh906616c2019-01-21 20:25:11 -08001269 << "threadid file:line] msg" << '\n';
1270 const string& file_header_string = file_header_stream.str();
1271
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001272 const size_t header_len = file_header_string.size();
Austin Schuh906616c2019-01-21 20:25:11 -08001273 fwrite(file_header_string.data(), 1, header_len, file_);
1274 file_length_ += header_len;
1275 bytes_since_flush_ += header_len;
1276 }
1277
1278 // Write to LOG file
1279 if ( !stop_writing ) {
1280 // fwrite() doesn't return an error when the disk is full, for
1281 // messages that are less than 4096 bytes. When the disk is full,
1282 // it returns the message length for messages that are less than
1283 // 4096 bytes. fwrite() returns 4096 for message lengths that are
1284 // greater than 4096, thereby indicating an error.
1285 errno = 0;
1286 fwrite(message, 1, message_len, file_);
1287 if ( FLAGS_stop_logging_if_full_disk &&
1288 errno == ENOSPC ) { // disk full, stop writing to disk
1289 stop_writing = true; // until the disk is
1290 return;
1291 } else {
1292 file_length_ += message_len;
1293 bytes_since_flush_ += message_len;
1294 }
1295 } else {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001296 if (CycleClock_Now() >= next_flush_time_) {
Austin Schuh906616c2019-01-21 20:25:11 -08001297 stop_writing = false; // check to see if disk has free space.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001298 }
Austin Schuh906616c2019-01-21 20:25:11 -08001299 return; // no need to flush
1300 }
1301
1302 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
1303 // or every "FLAGS_logbufsecs" seconds.
1304 if ( force_flush ||
1305 (bytes_since_flush_ >= 1000000) ||
1306 (CycleClock_Now() >= next_flush_time_) ) {
1307 FlushUnlocked();
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001308#ifdef GLOG_OS_LINUX
Austin Schuh906616c2019-01-21 20:25:11 -08001309 // Only consider files >= 3MiB
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001310 if (FLAGS_drop_log_memory && file_length_ >= (3U << 20U)) {
Austin Schuh906616c2019-01-21 20:25:11 -08001311 // Don't evict the most recent 1-2MiB so as not to impact a tailer
1312 // of the log file and to avoid page rounding issue on linux < 4.7
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001313 uint32 total_drop_length =
1314 (file_length_ & ~((1U << 20U) - 1U)) - (1U << 20U);
Austin Schuh906616c2019-01-21 20:25:11 -08001315 uint32 this_drop_length = total_drop_length - dropped_mem_length_;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001316 if (this_drop_length >= (2U << 20U)) {
Austin Schuh906616c2019-01-21 20:25:11 -08001317 // Only advise when >= 2MiB to drop
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001318# if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
1319 // 'posix_fadvise' introduced in API 21:
1320 // * https://android.googlesource.com/platform/bionic/+/6880f936173081297be0dc12f687d341b86a4cfa/libc/libc.map.txt#732
1321# else
1322 posix_fadvise(fileno(file_), static_cast<off_t>(dropped_mem_length_),
1323 static_cast<off_t>(this_drop_length),
Austin Schuh906616c2019-01-21 20:25:11 -08001324 POSIX_FADV_DONTNEED);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001325# endif
Austin Schuh906616c2019-01-21 20:25:11 -08001326 dropped_mem_length_ = total_drop_length;
1327 }
1328 }
1329#endif
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001330
1331 // Remove old logs
1332 if (log_cleaner.enabled()) {
1333 log_cleaner.Run(base_filename_selected_,
1334 base_filename_,
1335 filename_extension_);
1336 }
Austin Schuh906616c2019-01-21 20:25:11 -08001337 }
1338}
1339
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001340LogCleaner::LogCleaner() : enabled_(false), overdue_days_(7), next_cleanup_time_(0) {}
Austin Schuh906616c2019-01-21 20:25:11 -08001341
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001342void LogCleaner::Enable(unsigned int overdue_days) {
1343 enabled_ = true;
1344 overdue_days_ = overdue_days;
1345}
1346
1347void LogCleaner::Disable() {
1348 enabled_ = false;
1349}
1350
1351void LogCleaner::UpdateCleanUpTime() {
1352 const int64 next = (FLAGS_logcleansecs
1353 * 1000000); // in usec
1354 next_cleanup_time_ = CycleClock_Now() + UsecToCycles(next);
1355}
1356
1357void LogCleaner::Run(bool base_filename_selected,
1358 const string& base_filename,
1359 const string& filename_extension) {
1360 assert(enabled_);
1361 assert(!base_filename_selected || !base_filename.empty());
1362
1363 // avoid scanning logs too frequently
1364 if (CycleClock_Now() < next_cleanup_time_) {
1365 return;
1366 }
1367 UpdateCleanUpTime();
1368
1369 vector<string> dirs;
1370
1371 if (!base_filename_selected) {
1372 dirs = GetLoggingDirectories();
1373 } else {
1374 size_t pos = base_filename.find_last_of(possible_dir_delim, string::npos,
1375 sizeof(possible_dir_delim));
1376 if (pos != string::npos) {
1377 string dir = base_filename.substr(0, pos + 1);
1378 dirs.push_back(dir);
1379 } else {
1380 dirs.push_back(".");
1381 }
1382 }
1383
1384 for (size_t i = 0; i < dirs.size(); i++) {
1385 vector<string> logs = GetOverdueLogNames(dirs[i],
1386 overdue_days_,
1387 base_filename,
1388 filename_extension);
1389 for (size_t j = 0; j < logs.size(); j++) {
1390 static_cast<void>(unlink(logs[j].c_str()));
1391 }
1392 }
1393}
1394
1395vector<string> LogCleaner::GetOverdueLogNames(
1396 string log_directory, unsigned int days, const string& base_filename,
1397 const string& filename_extension) const {
1398 // The names of overdue logs.
1399 vector<string> overdue_log_names;
1400
1401 // Try to get all files within log_directory.
1402 DIR *dir;
1403 struct dirent *ent;
1404
1405 if ((dir = opendir(log_directory.c_str()))) {
1406 while ((ent = readdir(dir))) {
1407 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) {
1408 continue;
1409 }
1410
1411 string filepath = ent->d_name;
1412 const char* const dir_delim_end =
1413 possible_dir_delim + sizeof(possible_dir_delim);
1414
1415 if (!log_directory.empty() &&
1416 std::find(possible_dir_delim, dir_delim_end,
1417 log_directory[log_directory.size() - 1]) != dir_delim_end) {
1418 filepath = log_directory + filepath;
1419 }
1420
1421 if (IsLogFromCurrentProject(filepath, base_filename, filename_extension) &&
1422 IsLogLastModifiedOver(filepath, days)) {
1423 overdue_log_names.push_back(filepath);
1424 }
1425 }
1426 closedir(dir);
1427 }
1428
1429 return overdue_log_names;
1430}
1431
1432bool LogCleaner::IsLogFromCurrentProject(const string& filepath,
1433 const string& base_filename,
1434 const string& filename_extension) const {
1435 // We should remove duplicated delimiters from `base_filename`, e.g.,
1436 // before: "/tmp//<base_filename>.<create_time>.<pid>"
1437 // after: "/tmp/<base_filename>.<create_time>.<pid>"
1438 string cleaned_base_filename;
1439
1440 const char* const dir_delim_end =
1441 possible_dir_delim + sizeof(possible_dir_delim);
1442
1443 size_t real_filepath_size = filepath.size();
1444 for (size_t i = 0; i < base_filename.size(); ++i) {
1445 const char& c = base_filename[i];
1446
1447 if (cleaned_base_filename.empty()) {
1448 cleaned_base_filename += c;
1449 } else if (std::find(possible_dir_delim, dir_delim_end, c) ==
1450 dir_delim_end ||
1451 (!cleaned_base_filename.empty() &&
1452 c != cleaned_base_filename[cleaned_base_filename.size() - 1])) {
1453 cleaned_base_filename += c;
1454 }
1455 }
1456
1457 // Return early if the filename doesn't start with `cleaned_base_filename`.
1458 if (filepath.find(cleaned_base_filename) != 0) {
1459 return false;
1460 }
1461
1462 // Check if in the string `filename_extension` is right next to
1463 // `cleaned_base_filename` in `filepath` if the user
1464 // has set a custom filename extension.
1465 if (!filename_extension.empty()) {
1466 if (cleaned_base_filename.size() >= real_filepath_size) {
1467 return false;
1468 }
1469 // for origin version, `filename_extension` is middle of the `filepath`.
1470 string ext = filepath.substr(cleaned_base_filename.size(), filename_extension.size());
1471 if (ext == filename_extension) {
1472 cleaned_base_filename += filename_extension;
1473 }
1474 else {
1475 // for new version, `filename_extension` is right of the `filepath`.
1476 if (filename_extension.size() >= real_filepath_size) {
1477 return false;
1478 }
1479 real_filepath_size = filepath.size() - filename_extension.size();
1480 if (filepath.substr(real_filepath_size) != filename_extension) {
1481 return false;
1482 }
1483 }
1484 }
1485
1486 // The characters after `cleaned_base_filename` should match the format:
1487 // YYYYMMDD-HHMMSS.pid
1488 for (size_t i = cleaned_base_filename.size(); i < real_filepath_size; i++) {
1489 const char& c = filepath[i];
1490
1491 if (i <= cleaned_base_filename.size() + 7) { // 0 ~ 7 : YYYYMMDD
1492 if (c < '0' || c > '9') { return false; }
1493
1494 } else if (i == cleaned_base_filename.size() + 8) { // 8: -
1495 if (c != '-') { return false; }
1496
1497 } else if (i <= cleaned_base_filename.size() + 14) { // 9 ~ 14: HHMMSS
1498 if (c < '0' || c > '9') { return false; }
1499
1500 } else if (i == cleaned_base_filename.size() + 15) { // 15: .
1501 if (c != '.') { return false; }
1502
1503 } else if (i >= cleaned_base_filename.size() + 16) { // 16+: pid
1504 if (c < '0' || c > '9') { return false; }
1505 }
1506 }
1507
1508 return true;
1509}
1510
1511bool LogCleaner::IsLogLastModifiedOver(const string& filepath,
1512 unsigned int days) const {
1513 // Try to get the last modified time of this file.
1514 struct stat file_stat;
1515
1516 if (stat(filepath.c_str(), &file_stat) == 0) {
1517 const time_t seconds_in_a_day = 60 * 60 * 24;
1518 time_t last_modified_time = file_stat.st_mtime;
1519 time_t current_time = time(NULL);
1520 return difftime(current_time, last_modified_time) > days * seconds_in_a_day;
1521 }
1522
1523 // If failed to get file stat, don't return true!
1524 return false;
1525}
1526
1527} // namespace
Austin Schuh906616c2019-01-21 20:25:11 -08001528
1529// Static log data space to avoid alloc failures in a LOG(FATAL)
1530//
1531// Since multiple threads may call LOG(FATAL), and we want to preserve
1532// the data from the first call, we allocate two sets of space. One
1533// for exclusive use by the first thread, and one for shared use by
1534// all other threads.
1535static Mutex fatal_msg_lock;
1536static CrashReason crash_reason;
1537static bool fatal_msg_exclusive = true;
1538static LogMessage::LogMessageData fatal_msg_data_exclusive;
1539static LogMessage::LogMessageData fatal_msg_data_shared;
1540
1541#ifdef GLOG_THREAD_LOCAL_STORAGE
1542// Static thread-local log data space to use, because typically at most one
1543// LogMessageData object exists (in this case glog makes zero heap memory
1544// allocations).
1545static GLOG_THREAD_LOCAL_STORAGE bool thread_data_available = true;
1546
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001547#if defined(HAVE_ALIGNED_STORAGE) && __cplusplus >= 201103L
Austin Schuh906616c2019-01-21 20:25:11 -08001548static GLOG_THREAD_LOCAL_STORAGE
1549 std::aligned_storage<sizeof(LogMessage::LogMessageData),
1550 alignof(LogMessage::LogMessageData)>::type thread_msg_data;
1551#else
1552static GLOG_THREAD_LOCAL_STORAGE
1553 char thread_msg_data[sizeof(void*) + sizeof(LogMessage::LogMessageData)];
1554#endif // HAVE_ALIGNED_STORAGE
1555#endif // defined(GLOG_THREAD_LOCAL_STORAGE)
1556
1557LogMessage::LogMessageData::LogMessageData()
1558 : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) {
1559}
1560
1561LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001562 int64 ctr, void (LogMessage::*send_method)())
Austin Schuh906616c2019-01-21 20:25:11 -08001563 : allocated_(NULL) {
1564 Init(file, line, severity, send_method);
1565 data_->stream_.set_ctr(ctr);
1566}
1567
1568LogMessage::LogMessage(const char* file, int line,
1569 const CheckOpString& result)
1570 : allocated_(NULL) {
1571 Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
1572 stream() << "Check failed: " << (*result.str_) << " ";
1573}
1574
1575LogMessage::LogMessage(const char* file, int line)
1576 : allocated_(NULL) {
1577 Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
1578}
1579
1580LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
1581 : allocated_(NULL) {
1582 Init(file, line, severity, &LogMessage::SendToLog);
1583}
1584
1585LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1586 LogSink* sink, bool also_send_to_log)
1587 : allocated_(NULL) {
1588 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
1589 &LogMessage::SendToSink);
1590 data_->sink_ = sink; // override Init()'s setting to NULL
1591}
1592
1593LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1594 vector<string> *outvec)
1595 : allocated_(NULL) {
1596 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
1597 data_->outvec_ = outvec; // override Init()'s setting to NULL
1598}
1599
1600LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1601 string *message)
1602 : allocated_(NULL) {
1603 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
1604 data_->message_ = message; // override Init()'s setting to NULL
1605}
1606
1607void LogMessage::Init(const char* file,
1608 int line,
1609 LogSeverity severity,
1610 void (LogMessage::*send_method)()) {
1611 allocated_ = NULL;
1612 if (severity != GLOG_FATAL || !exit_on_dfatal) {
1613#ifdef GLOG_THREAD_LOCAL_STORAGE
1614 // No need for locking, because this is thread local.
1615 if (thread_data_available) {
1616 thread_data_available = false;
1617#ifdef HAVE_ALIGNED_STORAGE
1618 data_ = new (&thread_msg_data) LogMessageData;
1619#else
1620 const uintptr_t kAlign = sizeof(void*) - 1;
1621
1622 char* align_ptr =
1623 reinterpret_cast<char*>(reinterpret_cast<uintptr_t>(thread_msg_data + kAlign) & ~kAlign);
1624 data_ = new (align_ptr) LogMessageData;
1625 assert(reinterpret_cast<uintptr_t>(align_ptr) % sizeof(void*) == 0);
1626#endif
1627 } else {
1628 allocated_ = new LogMessageData();
1629 data_ = allocated_;
1630 }
1631#else // !defined(GLOG_THREAD_LOCAL_STORAGE)
1632 allocated_ = new LogMessageData();
1633 data_ = allocated_;
1634#endif // defined(GLOG_THREAD_LOCAL_STORAGE)
1635 data_->first_fatal_ = false;
1636 } else {
1637 MutexLock l(&fatal_msg_lock);
1638 if (fatal_msg_exclusive) {
1639 fatal_msg_exclusive = false;
1640 data_ = &fatal_msg_data_exclusive;
1641 data_->first_fatal_ = true;
1642 } else {
1643 data_ = &fatal_msg_data_shared;
1644 data_->first_fatal_ = false;
1645 }
1646 }
1647
Austin Schuh906616c2019-01-21 20:25:11 -08001648 data_->preserved_errno_ = errno;
1649 data_->severity_ = severity;
1650 data_->line_ = line;
1651 data_->send_method_ = send_method;
1652 data_->sink_ = NULL;
1653 data_->outvec_ = NULL;
1654 WallTime now = WallTime_Now();
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001655 time_t timestamp_now = static_cast<time_t>(now);
1656 logmsgtime_ = LogMessageTime(timestamp_now, now);
Austin Schuh906616c2019-01-21 20:25:11 -08001657
1658 data_->num_chars_to_log_ = 0;
1659 data_->num_chars_to_syslog_ = 0;
1660 data_->basename_ = const_basename(file);
1661 data_->fullname_ = file;
1662 data_->has_been_flushed_ = false;
1663
1664 // If specified, prepend a prefix to each line. For example:
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001665 // I20201018 160715 f5d4fbb0 logging.cc:1153]
1666 // (log level, GMT year, month, date, time, thread_id, file basename, line)
Austin Schuh906616c2019-01-21 20:25:11 -08001667 // We exclude the thread_id for the default thread.
1668 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001669 std::ios saved_fmt(NULL);
1670 saved_fmt.copyfmt(stream());
1671 stream().fill('0');
1672 #ifdef GLOG_CUSTOM_PREFIX_SUPPORT
1673 if (custom_prefix_callback == NULL) {
1674 #endif
1675 stream() << LogSeverityNames[severity][0];
1676 if (FLAGS_log_year_in_prefix) {
1677 stream() << setw(4) << 1900 + logmsgtime_.year();
1678 }
1679 stream() << setw(2) << 1 + logmsgtime_.month()
1680 << setw(2) << logmsgtime_.day()
1681 << ' '
1682 << setw(2) << logmsgtime_.hour() << ':'
1683 << setw(2) << logmsgtime_.min() << ':'
1684 << setw(2) << logmsgtime_.sec() << "."
1685 << setw(6) << logmsgtime_.usec()
1686 << ' '
1687 << setfill(' ') << setw(5)
1688 << static_cast<unsigned int>(GetTID()) << setfill('0')
1689 << ' '
1690 << data_->basename_ << ':' << data_->line_ << "] ";
1691 #ifdef GLOG_CUSTOM_PREFIX_SUPPORT
1692 } else {
1693 custom_prefix_callback(
1694 stream(),
1695 LogMessageInfo(LogSeverityNames[severity],
1696 data_->basename_, data_->line_, GetTID(),
1697 logmsgtime_),
1698 custom_prefix_callback_data
1699 );
1700 stream() << " ";
1701 }
1702 #endif
1703 stream().copyfmt(saved_fmt);
Austin Schuh906616c2019-01-21 20:25:11 -08001704 }
1705 data_->num_prefix_chars_ = data_->stream_.pcount();
1706
1707 if (!FLAGS_log_backtrace_at.empty()) {
1708 char fileline[128];
1709 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1710#ifdef HAVE_STACKTRACE
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001711 if (FLAGS_log_backtrace_at == fileline) {
Austin Schuh906616c2019-01-21 20:25:11 -08001712 string stacktrace;
1713 DumpStackTraceToString(&stacktrace);
1714 stream() << " (stacktrace:\n" << stacktrace << ") ";
1715 }
1716#endif
1717 }
1718}
1719
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001720const LogMessageTime& LogMessage::getLogMessageTime() const {
1721 return logmsgtime_;
1722}
1723
Austin Schuh906616c2019-01-21 20:25:11 -08001724LogMessage::~LogMessage() {
1725 Flush();
1726#ifdef GLOG_THREAD_LOCAL_STORAGE
1727 if (data_ == static_cast<void*>(&thread_msg_data)) {
1728 data_->~LogMessageData();
1729 thread_data_available = true;
1730 }
1731 else {
1732 delete allocated_;
1733 }
1734#else // !defined(GLOG_THREAD_LOCAL_STORAGE)
1735 delete allocated_;
1736#endif // defined(GLOG_THREAD_LOCAL_STORAGE)
1737}
1738
1739int LogMessage::preserved_errno() const {
1740 return data_->preserved_errno_;
1741}
1742
1743ostream& LogMessage::stream() {
1744 return data_->stream_;
1745}
1746
1747// Flush buffered message, called by the destructor, or any other function
1748// that needs to synchronize the log.
1749void LogMessage::Flush() {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001750 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel) {
Austin Schuh906616c2019-01-21 20:25:11 -08001751 return;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001752 }
Austin Schuh906616c2019-01-21 20:25:11 -08001753
1754 data_->num_chars_to_log_ = data_->stream_.pcount();
1755 data_->num_chars_to_syslog_ =
1756 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1757
1758 // Do we need to add a \n to the end of this message?
1759 bool append_newline =
1760 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1761 char original_final_char = '\0';
1762
1763 // If we do need to add a \n, we'll do it by violating the memory of the
1764 // ostrstream buffer. This is quick, and we'll make sure to undo our
1765 // modification before anything else is done with the ostrstream. It
1766 // would be preferable not to do things this way, but it seems to be
1767 // the best way to deal with this.
1768 if (append_newline) {
1769 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1770 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1771 }
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001772 data_->message_text_[data_->num_chars_to_log_] = '\0';
Austin Schuh906616c2019-01-21 20:25:11 -08001773
1774 // Prevent any subtle race conditions by wrapping a mutex lock around
1775 // the actual logging action per se.
1776 {
1777 MutexLock l(&log_mutex);
1778 (this->*(data_->send_method_))();
1779 ++num_messages_[static_cast<int>(data_->severity_)];
1780 }
1781 LogDestination::WaitForSinks(data_);
1782
1783 if (append_newline) {
1784 // Fix the ostrstream back how it was before we screwed with it.
1785 // It's 99.44% certain that we don't need to worry about doing this.
1786 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1787 }
1788
1789 // If errno was already set before we enter the logging call, we'll
1790 // set it back to that value when we return from the logging call.
1791 // It happens often that we log an error message after a syscall
1792 // failure, which can potentially set the errno to some other
1793 // values. We would like to preserve the original errno.
1794 if (data_->preserved_errno_ != 0) {
1795 errno = data_->preserved_errno_;
1796 }
1797
1798 // Note that this message is now safely logged. If we're asked to flush
1799 // again, as a result of destruction, say, we'll do nothing on future calls.
1800 data_->has_been_flushed_ = true;
1801}
1802
1803// Copy of first FATAL log message so that we can print it out again
1804// after all the stack traces. To preserve legacy behavior, we don't
1805// use fatal_msg_data_exclusive.
1806static time_t fatal_time;
1807static char fatal_message[256];
1808
1809void ReprintFatalMessage() {
1810 if (fatal_message[0]) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001811 const size_t n = strlen(fatal_message);
Austin Schuh906616c2019-01-21 20:25:11 -08001812 if (!FLAGS_logtostderr) {
1813 // Also write to stderr (don't color to avoid terminal checks)
1814 WriteToStderr(fatal_message, n);
1815 }
1816 LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1817 }
1818}
1819
1820// L >= log_mutex (callers must hold the log_mutex).
1821void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1822 static bool already_warned_before_initgoogle = false;
1823
1824 log_mutex.AssertHeld();
1825
1826 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1827 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1828
1829 // Messages of a given severity get logged to lower severity logs, too
1830
1831 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1832 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1833 "written to STDERR\n";
1834 WriteToStderr(w, strlen(w));
1835 already_warned_before_initgoogle = true;
1836 }
1837
1838 // global flag: never log to file if set. Also -- don't log to a
1839 // file if we haven't parsed the command line flags to get the
1840 // program name.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001841 if (FLAGS_logtostderr || FLAGS_logtostdout || !IsGoogleLoggingInitialized()) {
1842 if (FLAGS_logtostdout) {
1843 ColoredWriteToStdout(data_->severity_, data_->message_text_,
1844 data_->num_chars_to_log_);
1845 } else {
1846 ColoredWriteToStderr(data_->severity_, data_->message_text_,
1847 data_->num_chars_to_log_);
1848 }
Austin Schuh906616c2019-01-21 20:25:11 -08001849
1850 // this could be protected by a flag if necessary.
1851 LogDestination::LogToSinks(data_->severity_,
1852 data_->fullname_, data_->basename_,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001853 data_->line_, logmsgtime_,
Austin Schuh906616c2019-01-21 20:25:11 -08001854 data_->message_text_ + data_->num_prefix_chars_,
1855 (data_->num_chars_to_log_ -
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001856 data_->num_prefix_chars_ - 1) );
Austin Schuh906616c2019-01-21 20:25:11 -08001857 } else {
Austin Schuh906616c2019-01-21 20:25:11 -08001858 // log this message to all log files of severity <= severity_
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001859 LogDestination::LogToAllLogfiles(data_->severity_, logmsgtime_.timestamp(),
Austin Schuh906616c2019-01-21 20:25:11 -08001860 data_->message_text_,
1861 data_->num_chars_to_log_);
1862
1863 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001864 data_->num_chars_to_log_,
1865 data_->num_prefix_chars_);
Austin Schuh906616c2019-01-21 20:25:11 -08001866 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1867 data_->num_chars_to_log_);
1868 LogDestination::LogToSinks(data_->severity_,
1869 data_->fullname_, data_->basename_,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001870 data_->line_, logmsgtime_,
Austin Schuh906616c2019-01-21 20:25:11 -08001871 data_->message_text_ + data_->num_prefix_chars_,
1872 (data_->num_chars_to_log_
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001873 - data_->num_prefix_chars_ - 1) );
Austin Schuh906616c2019-01-21 20:25:11 -08001874 // NOTE: -1 removes trailing \n
1875 }
1876
1877 // If we log a FATAL message, flush all the log destinations, then toss
1878 // a signal for others to catch. We leave the logs in a state that
1879 // someone else can use them (as long as they flush afterwards)
1880 if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1881 if (data_->first_fatal_) {
1882 // Store crash information so that it is accessible from within signal
1883 // handlers that may be invoked later.
1884 RecordCrashReason(&crash_reason);
1885 SetCrashReason(&crash_reason);
1886
1887 // Store shortened fatal message for other logs and GWQ status
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001888 const size_t copy = min(data_->num_chars_to_log_,
Austin Schuh906616c2019-01-21 20:25:11 -08001889 sizeof(fatal_message)-1);
1890 memcpy(fatal_message, data_->message_text_, copy);
1891 fatal_message[copy] = '\0';
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001892 fatal_time = logmsgtime_.timestamp();
Austin Schuh906616c2019-01-21 20:25:11 -08001893 }
1894
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001895 if (!FLAGS_logtostderr && !FLAGS_logtostdout) {
Austin Schuh906616c2019-01-21 20:25:11 -08001896 for (int i = 0; i < NUM_SEVERITIES; ++i) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001897 if (LogDestination::log_destinations_[i]) {
Austin Schuh906616c2019-01-21 20:25:11 -08001898 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001899 }
Austin Schuh906616c2019-01-21 20:25:11 -08001900 }
1901 }
1902
1903 // release the lock that our caller (directly or indirectly)
1904 // LogMessage::~LogMessage() grabbed so that signal handlers
1905 // can use the logging facility. Alternately, we could add
1906 // an entire unsafe logging interface to bypass locking
1907 // for signal handlers but this seems simpler.
1908 log_mutex.Unlock();
1909 LogDestination::WaitForSinks(data_);
1910
1911 const char* message = "*** Check failure stack trace: ***\n";
1912 if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1913 // Ignore errors.
1914 }
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001915#if defined(__ANDROID__)
1916 // ANDROID_LOG_FATAL as this message is of FATAL severity.
1917 __android_log_write(ANDROID_LOG_FATAL,
1918 glog_internal_namespace_::ProgramInvocationShortName(),
1919 message);
1920#endif
Austin Schuh906616c2019-01-21 20:25:11 -08001921 Fail();
1922 }
1923}
1924
1925void LogMessage::RecordCrashReason(
1926 glog_internal_namespace_::CrashReason* reason) {
1927 reason->filename = fatal_msg_data_exclusive.fullname_;
1928 reason->line_number = fatal_msg_data_exclusive.line_;
1929 reason->message = fatal_msg_data_exclusive.message_text_ +
1930 fatal_msg_data_exclusive.num_prefix_chars_;
1931#ifdef HAVE_STACKTRACE
1932 // Retrieve the stack trace, omitting the logging frames that got us here.
1933 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1934#else
1935 reason->depth = 0;
1936#endif
1937}
1938
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001939GLOG_EXPORT logging_fail_func_t g_logging_fail_func =
1940 reinterpret_cast<logging_fail_func_t>(&abort);
Austin Schuh906616c2019-01-21 20:25:11 -08001941
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001942void InstallFailureFunction(logging_fail_func_t fail_func) {
1943 g_logging_fail_func = fail_func;
Austin Schuh906616c2019-01-21 20:25:11 -08001944}
1945
1946void LogMessage::Fail() {
1947 g_logging_fail_func();
1948}
1949
1950// L >= log_mutex (callers must hold the log_mutex).
1951void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1952 if (data_->sink_ != NULL) {
1953 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1954 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1955 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001956 data_->line_, logmsgtime_,
Austin Schuh906616c2019-01-21 20:25:11 -08001957 data_->message_text_ + data_->num_prefix_chars_,
1958 (data_->num_chars_to_log_ -
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001959 data_->num_prefix_chars_ - 1) );
Austin Schuh906616c2019-01-21 20:25:11 -08001960 }
1961}
1962
1963// L >= log_mutex (callers must hold the log_mutex).
1964void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1965 SendToSink();
1966 SendToLog();
1967}
1968
1969// L >= log_mutex (callers must hold the log_mutex).
1970void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1971 if (data_->outvec_ != NULL) {
1972 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1973 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1974 // Omit prefix of message and trailing newline when recording in outvec_.
1975 const char *start = data_->message_text_ + data_->num_prefix_chars_;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001976 size_t len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
Austin Schuh906616c2019-01-21 20:25:11 -08001977 data_->outvec_->push_back(string(start, len));
1978 } else {
1979 SendToLog();
1980 }
1981}
1982
1983void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1984 if (data_->message_ != NULL) {
1985 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1986 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1987 // Omit prefix of message and trailing newline when writing to message_.
1988 const char *start = data_->message_text_ + data_->num_prefix_chars_;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001989 size_t len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
Austin Schuh906616c2019-01-21 20:25:11 -08001990 data_->message_->assign(start, len);
1991 }
1992 SendToLog();
1993}
1994
1995// L >= log_mutex (callers must hold the log_mutex).
1996void LogMessage::SendToSyslogAndLog() {
1997#ifdef HAVE_SYSLOG_H
1998 // Before any calls to syslog(), make a single call to openlog()
1999 static bool openlog_already_called = false;
2000 if (!openlog_already_called) {
2001 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
2002 LOG_CONS | LOG_NDELAY | LOG_PID,
2003 LOG_USER);
2004 openlog_already_called = true;
2005 }
2006
2007 // This array maps Google severity levels to syslog levels
2008 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
2009 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
2010 int(data_->num_chars_to_syslog_),
2011 data_->message_text_ + data_->num_prefix_chars_);
2012 SendToLog();
2013#else
2014 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
2015#endif
2016}
2017
2018base::Logger* base::GetLogger(LogSeverity severity) {
2019 MutexLock l(&log_mutex);
2020 return LogDestination::log_destination(severity)->logger_;
2021}
2022
2023void base::SetLogger(LogSeverity severity, base::Logger* logger) {
2024 MutexLock l(&log_mutex);
2025 LogDestination::log_destination(severity)->logger_ = logger;
2026}
2027
2028// L < log_mutex. Acquires and releases mutex_.
2029int64 LogMessage::num_messages(int severity) {
2030 MutexLock l(&log_mutex);
2031 return num_messages_[severity];
2032}
2033
2034// Output the COUNTER value. This is only valid if ostream is a
2035// LogStream.
2036ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
2037#ifdef DISABLE_RTTI
2038 LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
2039#else
2040 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
2041#endif
2042 CHECK(log && log == log->self())
2043 << "You must not use COUNTER with non-glog ostream";
2044 os << log->ctr();
2045 return os;
2046}
2047
2048ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002049 LogSeverity severity, int64 ctr,
Austin Schuh906616c2019-01-21 20:25:11 -08002050 void (LogMessage::*send_method)())
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002051 : LogMessage(file, line, severity, ctr, send_method) {}
Austin Schuh906616c2019-01-21 20:25:11 -08002052
2053ErrnoLogMessage::~ErrnoLogMessage() {
2054 // Don't access errno directly because it may have been altered
2055 // while streaming the message.
2056 stream() << ": " << StrError(preserved_errno()) << " ["
2057 << preserved_errno() << "]";
2058}
2059
2060void FlushLogFiles(LogSeverity min_severity) {
2061 LogDestination::FlushLogFiles(min_severity);
2062}
2063
2064void FlushLogFilesUnsafe(LogSeverity min_severity) {
2065 LogDestination::FlushLogFilesUnsafe(min_severity);
2066}
2067
2068void SetLogDestination(LogSeverity severity, const char* base_filename) {
2069 LogDestination::SetLogDestination(severity, base_filename);
2070}
2071
2072void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
2073 LogDestination::SetLogSymlink(severity, symlink_basename);
2074}
2075
2076LogSink::~LogSink() {
2077}
2078
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002079void LogSink::send(LogSeverity severity, const char* full_filename,
2080 const char* base_filename, int line,
2081 const LogMessageTime& time, const char* message,
2082 size_t message_len) {
2083#if defined(__GNUC__)
2084#pragma GCC diagnostic push
2085#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
2086#elif defined(_MSC_VER)
2087#pragma warning(push)
2088#pragma warning(disable : 4996)
2089#endif // __GNUC__
2090 send(severity, full_filename, base_filename, line, &time.tm(), message,
2091 message_len);
2092#if defined(__GNUC__)
2093#pragma GCC diagnostic pop
2094#elif defined(_MSC_VER)
2095#pragma warning(pop)
2096#endif // __GNUC__
2097}
2098
2099void LogSink::send(LogSeverity severity, const char* full_filename,
2100 const char* base_filename, int line, const std::tm* t,
2101 const char* message, size_t message_len) {
2102 (void)severity;
2103 (void)full_filename;
2104 (void)base_filename;
2105 (void)line;
2106 (void)t;
2107 (void)message;
2108 (void)message_len;
2109}
2110
Austin Schuh906616c2019-01-21 20:25:11 -08002111void LogSink::WaitTillSent() {
2112 // noop default
2113}
2114
2115string LogSink::ToString(LogSeverity severity, const char* file, int line,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002116 const LogMessageTime& logmsgtime, const char* message,
2117 size_t message_len) {
Austin Schuh906616c2019-01-21 20:25:11 -08002118 ostringstream stream(string(message, message_len));
2119 stream.fill('0');
2120
Austin Schuh906616c2019-01-21 20:25:11 -08002121 stream << LogSeverityNames[severity][0]
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002122 << setw(4) << 1900 + logmsgtime.year()
2123 << setw(2) << 1 + logmsgtime.month()
2124 << setw(2) << logmsgtime.day()
Austin Schuh906616c2019-01-21 20:25:11 -08002125 << ' '
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002126 << setw(2) << logmsgtime.hour() << ':'
2127 << setw(2) << logmsgtime.min() << ':'
2128 << setw(2) << logmsgtime.sec() << '.'
2129 << setw(6) << logmsgtime.usec()
Austin Schuh906616c2019-01-21 20:25:11 -08002130 << ' '
2131 << setfill(' ') << setw(5) << GetTID() << setfill('0')
2132 << ' '
2133 << file << ':' << line << "] ";
2134
2135 stream << string(message, message_len);
2136 return stream.str();
2137}
2138
2139void AddLogSink(LogSink *destination) {
2140 LogDestination::AddLogSink(destination);
2141}
2142
2143void RemoveLogSink(LogSink *destination) {
2144 LogDestination::RemoveLogSink(destination);
2145}
2146
2147void SetLogFilenameExtension(const char* ext) {
2148 LogDestination::SetLogFilenameExtension(ext);
2149}
2150
2151void SetStderrLogging(LogSeverity min_severity) {
2152 LogDestination::SetStderrLogging(min_severity);
2153}
2154
2155void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
2156 LogDestination::SetEmailLogging(min_severity, addresses);
2157}
2158
2159void LogToStderr() {
2160 LogDestination::LogToStderr();
2161}
2162
2163namespace base {
2164namespace internal {
2165
2166bool GetExitOnDFatal();
2167bool GetExitOnDFatal() {
2168 MutexLock l(&log_mutex);
2169 return exit_on_dfatal;
2170}
2171
2172// Determines whether we exit the program for a LOG(DFATAL) message in
2173// debug mode. It does this by skipping the call to Fail/FailQuietly.
2174// This is intended for testing only.
2175//
2176// This can have some effects on LOG(FATAL) as well. Failure messages
2177// are always allocated (rather than sharing a buffer), the crash
2178// reason is not recorded, the "gwq" status message is not updated,
2179// and the stack trace is not recorded. The LOG(FATAL) *will* still
2180// exit the program. Since this function is used only in testing,
2181// these differences are acceptable.
2182void SetExitOnDFatal(bool value);
2183void SetExitOnDFatal(bool value) {
2184 MutexLock l(&log_mutex);
2185 exit_on_dfatal = value;
2186}
2187
2188} // namespace internal
2189} // namespace base
2190
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002191#ifndef GLOG_OS_EMSCRIPTEN
Austin Schuh906616c2019-01-21 20:25:11 -08002192// Shell-escaping as we need to shell out ot /bin/mail.
2193static const char kDontNeedShellEscapeChars[] =
2194 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2195 "abcdefghijklmnopqrstuvwxyz"
2196 "0123456789+-_.=/:,@";
2197
2198static string ShellEscape(const string& src) {
2199 string result;
2200 if (!src.empty() && // empty string needs quotes
2201 src.find_first_not_of(kDontNeedShellEscapeChars) == string::npos) {
2202 // only contains chars that don't need quotes; it's fine
2203 result.assign(src);
2204 } else if (src.find_first_of('\'') == string::npos) {
2205 // no single quotes; just wrap it in single quotes
2206 result.assign("'");
2207 result.append(src);
2208 result.append("'");
2209 } else {
2210 // needs double quote escaping
2211 result.assign("\"");
2212 for (size_t i = 0; i < src.size(); ++i) {
2213 switch (src[i]) {
2214 case '\\':
2215 case '$':
2216 case '"':
2217 case '`':
2218 result.append("\\");
2219 }
2220 result.append(src, i, 1);
2221 }
2222 result.append("\"");
2223 }
2224 return result;
2225}
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002226#endif
Austin Schuh906616c2019-01-21 20:25:11 -08002227
2228// use_logging controls whether the logging functions LOG/VLOG are used
2229// to log errors. It should be set to false when the caller holds the
2230// log_mutex.
2231static bool SendEmailInternal(const char*dest, const char *subject,
2232 const char*body, bool use_logging) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002233#ifndef GLOG_OS_EMSCRIPTEN
Austin Schuh906616c2019-01-21 20:25:11 -08002234 if (dest && *dest) {
2235 if ( use_logging ) {
2236 VLOG(1) << "Trying to send TITLE:" << subject
2237 << " BODY:" << body << " to " << dest;
2238 } else {
2239 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
2240 subject, body, dest);
2241 }
2242
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002243 string logmailer = FLAGS_logmailer;
2244 if (logmailer.empty()) {
2245 logmailer = "/bin/mail";
2246 }
Austin Schuh906616c2019-01-21 20:25:11 -08002247 string cmd =
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002248 logmailer + " -s" +
Austin Schuh906616c2019-01-21 20:25:11 -08002249 ShellEscape(subject) + " " + ShellEscape(dest);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002250 if (use_logging) {
2251 VLOG(4) << "Mailing command: " << cmd;
2252 }
Austin Schuh906616c2019-01-21 20:25:11 -08002253
2254 FILE* pipe = popen(cmd.c_str(), "w");
2255 if (pipe != NULL) {
2256 // Add the body if we have one
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002257 if (body) {
Austin Schuh906616c2019-01-21 20:25:11 -08002258 fwrite(body, sizeof(char), strlen(body), pipe);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002259 }
Austin Schuh906616c2019-01-21 20:25:11 -08002260 bool ok = pclose(pipe) != -1;
2261 if ( !ok ) {
2262 if ( use_logging ) {
2263 LOG(ERROR) << "Problems sending mail to " << dest << ": "
2264 << StrError(errno);
2265 } else {
2266 fprintf(stderr, "Problems sending mail to %s: %s\n",
2267 dest, StrError(errno).c_str());
2268 }
2269 }
2270 return ok;
2271 } else {
2272 if ( use_logging ) {
2273 LOG(ERROR) << "Unable to send mail to " << dest;
2274 } else {
2275 fprintf(stderr, "Unable to send mail to %s\n", dest);
2276 }
2277 }
2278 }
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002279#else
2280 (void)dest;
2281 (void)subject;
2282 (void)body;
2283 (void)use_logging;
2284 LOG(WARNING) << "Email support not available; not sending message";
2285#endif
Austin Schuh906616c2019-01-21 20:25:11 -08002286 return false;
2287}
2288
2289bool SendEmail(const char*dest, const char *subject, const char*body){
2290 return SendEmailInternal(dest, subject, body, true);
2291}
2292
2293static void GetTempDirectories(vector<string>* list) {
2294 list->clear();
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002295#ifdef GLOG_OS_WINDOWS
Austin Schuh906616c2019-01-21 20:25:11 -08002296 // On windows we'll try to find a directory in this order:
2297 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
2298 // C:/TMP/
2299 // C:/TEMP/
2300 // C:/WINDOWS/ or C:/WINNT/
2301 // .
2302 char tmp[MAX_PATH];
2303 if (GetTempPathA(MAX_PATH, tmp))
2304 list->push_back(tmp);
2305 list->push_back("C:\\tmp\\");
2306 list->push_back("C:\\temp\\");
2307#else
2308 // Directories, in order of preference. If we find a dir that
2309 // exists, we stop adding other less-preferred dirs
2310 const char * candidates[] = {
2311 // Non-null only during unittest/regtest
2312 getenv("TEST_TMPDIR"),
2313
2314 // Explicitly-supplied temp dirs
2315 getenv("TMPDIR"), getenv("TMP"),
2316
2317 // If all else fails
2318 "/tmp",
2319 };
2320
2321 for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
2322 const char *d = candidates[i];
2323 if (!d) continue; // Empty env var
2324
2325 // Make sure we don't surprise anyone who's expecting a '/'
2326 string dstr = d;
2327 if (dstr[dstr.size() - 1] != '/') {
2328 dstr += "/";
2329 }
2330 list->push_back(dstr);
2331
2332 struct stat statbuf;
2333 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
2334 // We found a dir that exists - we're done.
2335 return;
2336 }
2337 }
2338
2339#endif
2340}
2341
2342static vector<string>* logging_directories_list;
2343
2344const vector<string>& GetLoggingDirectories() {
2345 // Not strictly thread-safe but we're called early in InitGoogle().
2346 if (logging_directories_list == NULL) {
2347 logging_directories_list = new vector<string>;
2348
2349 if ( !FLAGS_log_dir.empty() ) {
2350 // A dir was specified, we should use it
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002351 logging_directories_list->push_back(FLAGS_log_dir);
Austin Schuh906616c2019-01-21 20:25:11 -08002352 } else {
2353 GetTempDirectories(logging_directories_list);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002354#ifdef GLOG_OS_WINDOWS
Austin Schuh906616c2019-01-21 20:25:11 -08002355 char tmp[MAX_PATH];
2356 if (GetWindowsDirectoryA(tmp, MAX_PATH))
2357 logging_directories_list->push_back(tmp);
2358 logging_directories_list->push_back(".\\");
2359#else
2360 logging_directories_list->push_back("./");
2361#endif
2362 }
2363 }
2364 return *logging_directories_list;
2365}
2366
2367void TestOnly_ClearLoggingDirectoriesList() {
2368 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
2369 "called from test code.\n");
2370 delete logging_directories_list;
2371 logging_directories_list = NULL;
2372}
2373
2374void GetExistingTempDirectories(vector<string>* list) {
2375 GetTempDirectories(list);
2376 vector<string>::iterator i_dir = list->begin();
2377 while( i_dir != list->end() ) {
2378 // zero arg to access means test for existence; no constant
2379 // defined on windows
2380 if ( access(i_dir->c_str(), 0) ) {
2381 i_dir = list->erase(i_dir);
2382 } else {
2383 ++i_dir;
2384 }
2385 }
2386}
2387
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002388void TruncateLogFile(const char *path, uint64 limit, uint64 keep) {
Austin Schuh906616c2019-01-21 20:25:11 -08002389#ifdef HAVE_UNISTD_H
2390 struct stat statbuf;
2391 const int kCopyBlockSize = 8 << 10;
2392 char copybuf[kCopyBlockSize];
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002393 off_t read_offset, write_offset;
Austin Schuh906616c2019-01-21 20:25:11 -08002394 // Don't follow symlinks unless they're our own fd symlinks in /proc
2395 int flags = O_RDWR;
2396 // TODO(hamaji): Support other environments.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002397#ifdef GLOG_OS_LINUX
Austin Schuh906616c2019-01-21 20:25:11 -08002398 const char *procfd_prefix = "/proc/self/fd/";
2399 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
2400#endif
2401
2402 int fd = open(path, flags);
2403 if (fd == -1) {
2404 if (errno == EFBIG) {
2405 // The log file in question has got too big for us to open. The
2406 // real fix for this would be to compile logging.cc (or probably
2407 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
2408 // rather scary.
2409 // Instead just truncate the file to something we can manage
2410 if (truncate(path, 0) == -1) {
2411 PLOG(ERROR) << "Unable to truncate " << path;
2412 } else {
2413 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
2414 }
2415 } else {
2416 PLOG(ERROR) << "Unable to open " << path;
2417 }
2418 return;
2419 }
2420
2421 if (fstat(fd, &statbuf) == -1) {
2422 PLOG(ERROR) << "Unable to fstat()";
2423 goto out_close_fd;
2424 }
2425
2426 // See if the path refers to a regular file bigger than the
2427 // specified limit
2428 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002429 if (statbuf.st_size <= static_cast<off_t>(limit)) goto out_close_fd;
2430 if (statbuf.st_size <= static_cast<off_t>(keep)) goto out_close_fd;
Austin Schuh906616c2019-01-21 20:25:11 -08002431
2432 // This log file is too large - we need to truncate it
2433 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
2434
2435 // Copy the last "keep" bytes of the file to the beginning of the file
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002436 read_offset = statbuf.st_size - static_cast<off_t>(keep);
Austin Schuh906616c2019-01-21 20:25:11 -08002437 write_offset = 0;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002438 ssize_t bytesin, bytesout;
Austin Schuh906616c2019-01-21 20:25:11 -08002439 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002440 bytesout = pwrite(fd, copybuf, static_cast<size_t>(bytesin), write_offset);
Austin Schuh906616c2019-01-21 20:25:11 -08002441 if (bytesout == -1) {
2442 PLOG(ERROR) << "Unable to write to " << path;
2443 break;
2444 } else if (bytesout != bytesin) {
2445 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
2446 }
2447 read_offset += bytesin;
2448 write_offset += bytesout;
2449 }
2450 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
2451
2452 // Truncate the remainder of the file. If someone else writes to the
2453 // end of the file after our last read() above, we lose their latest
2454 // data. Too bad ...
2455 if (ftruncate(fd, write_offset) == -1) {
2456 PLOG(ERROR) << "Unable to truncate " << path;
2457 }
2458
2459 out_close_fd:
2460 close(fd);
2461#else
2462 LOG(ERROR) << "No log truncation support.";
2463#endif
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002464 }
Austin Schuh906616c2019-01-21 20:25:11 -08002465
2466void TruncateStdoutStderr() {
2467#ifdef HAVE_UNISTD_H
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002468 uint64 limit = MaxLogSize() << 20U;
2469 uint64 keep = 1U << 20U;
Austin Schuh906616c2019-01-21 20:25:11 -08002470 TruncateLogFile("/proc/self/fd/1", limit, keep);
2471 TruncateLogFile("/proc/self/fd/2", limit, keep);
2472#else
2473 LOG(ERROR) << "No log truncation support.";
2474#endif
2475}
2476
2477
2478// Helper functions for string comparisons.
2479#define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
2480 string* Check##func##expected##Impl(const char* s1, const char* s2, \
2481 const char* names) { \
2482 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
2483 if (equal == expected) return NULL; \
2484 else { \
2485 ostringstream ss; \
2486 if (!s1) s1 = ""; \
2487 if (!s2) s2 = ""; \
2488 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
2489 return new string(ss.str()); \
2490 } \
2491 }
2492DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
2493DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
2494DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
2495DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
2496#undef DEFINE_CHECK_STROP_IMPL
2497
2498int posix_strerror_r(int err, char *buf, size_t len) {
2499 // Sanity check input parameters
2500 if (buf == NULL || len <= 0) {
2501 errno = EINVAL;
2502 return -1;
2503 }
2504
2505 // Reset buf and errno, and try calling whatever version of strerror_r()
2506 // is implemented by glibc
2507 buf[0] = '\000';
2508 int old_errno = errno;
2509 errno = 0;
2510 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
2511
2512 // Both versions set errno on failure
2513 if (errno) {
2514 // Should already be there, but better safe than sorry
2515 buf[0] = '\000';
2516 return -1;
2517 }
2518 errno = old_errno;
2519
2520 // POSIX is vague about whether the string will be terminated, although
2521 // is indirectly implies that typically ERANGE will be returned, instead
2522 // of truncating the string. This is different from the GNU implementation.
2523 // We play it safe by always terminating the string explicitly.
2524 buf[len-1] = '\000';
2525
2526 // If the function succeeded, we can use its exit code to determine the
2527 // semantics implemented by glibc
2528 if (!rc) {
2529 return 0;
2530 } else {
2531 // GNU semantics detected
2532 if (rc == buf) {
2533 return 0;
2534 } else {
2535 buf[0] = '\000';
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002536#if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || defined(GLOG_OS_OPENBSD)
Austin Schuh906616c2019-01-21 20:25:11 -08002537 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
2538 // This means an error on MacOSX or FreeBSD.
2539 return -1;
2540 }
2541#endif
2542 strncat(buf, rc, len-1);
2543 return 0;
2544 }
2545 }
2546}
2547
2548string StrError(int err) {
2549 char buf[100];
2550 int rc = posix_strerror_r(err, buf, sizeof(buf));
2551 if ((rc < 0) || (buf[0] == '\000')) {
2552 snprintf(buf, sizeof(buf), "Error number %d", err);
2553 }
2554 return buf;
2555}
2556
2557LogMessageFatal::LogMessageFatal(const char* file, int line) :
2558 LogMessage(file, line, GLOG_FATAL) {}
2559
2560LogMessageFatal::LogMessageFatal(const char* file, int line,
2561 const CheckOpString& result) :
2562 LogMessage(file, line, result) {}
2563
2564LogMessageFatal::~LogMessageFatal() {
2565 Flush();
2566 LogMessage::Fail();
2567}
2568
2569namespace base {
2570
2571CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
2572 : stream_(new ostringstream) {
2573 *stream_ << exprtext << " (";
2574}
2575
2576CheckOpMessageBuilder::~CheckOpMessageBuilder() {
2577 delete stream_;
2578}
2579
2580ostream* CheckOpMessageBuilder::ForVar2() {
2581 *stream_ << " vs. ";
2582 return stream_;
2583}
2584
2585string* CheckOpMessageBuilder::NewString() {
2586 *stream_ << ")";
2587 return new string(stream_->str());
2588}
2589
2590} // namespace base
2591
2592template <>
2593void MakeCheckOpValueString(std::ostream* os, const char& v) {
2594 if (v >= 32 && v <= 126) {
2595 (*os) << "'" << v << "'";
2596 } else {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002597 (*os) << "char value " << static_cast<short>(v);
Austin Schuh906616c2019-01-21 20:25:11 -08002598 }
2599}
2600
2601template <>
2602void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
2603 if (v >= 32 && v <= 126) {
2604 (*os) << "'" << v << "'";
2605 } else {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002606 (*os) << "signed char value " << static_cast<short>(v);
Austin Schuh906616c2019-01-21 20:25:11 -08002607 }
2608}
2609
2610template <>
2611void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
2612 if (v >= 32 && v <= 126) {
2613 (*os) << "'" << v << "'";
2614 } else {
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002615 (*os) << "unsigned char value " << static_cast<unsigned short>(v);
Austin Schuh906616c2019-01-21 20:25:11 -08002616 }
2617}
2618
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002619#if defined(HAVE_CXX11_NULLPTR_T) && __cplusplus >= 201103L
2620template <>
2621void MakeCheckOpValueString(std::ostream* os, const std::nullptr_t& /*v*/) {
2622 (*os) << "nullptr";
2623}
2624#endif // defined(HAVE_CXX11_NULLPTR_T)
2625
Austin Schuh906616c2019-01-21 20:25:11 -08002626void InitGoogleLogging(const char* argv0) {
2627 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
2628}
2629
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002630#ifdef GLOG_CUSTOM_PREFIX_SUPPORT
2631void InitGoogleLogging(const char* argv0,
2632 CustomPrefixCallback prefix_callback,
2633 void* prefix_callback_data) {
2634 custom_prefix_callback = prefix_callback;
2635 custom_prefix_callback_data = prefix_callback_data;
2636 InitGoogleLogging(argv0);
2637}
2638#endif
2639
Austin Schuh906616c2019-01-21 20:25:11 -08002640void ShutdownGoogleLogging() {
2641 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
2642 LogDestination::DeleteLogDestinations();
2643 delete logging_directories_list;
2644 logging_directories_list = NULL;
2645}
2646
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07002647void EnableLogCleaner(unsigned int overdue_days) {
2648 log_cleaner.Enable(overdue_days);
2649}
2650
2651void DisableLogCleaner() {
2652 log_cleaner.Disable();
2653}
2654
2655LogMessageTime::LogMessageTime()
2656 : time_struct_(), timestamp_(0), usecs_(0), gmtoffset_(0) {}
2657
2658LogMessageTime::LogMessageTime(std::tm t) {
2659 std::time_t timestamp = std::mktime(&t);
2660 init(t, timestamp, 0);
2661}
2662
2663LogMessageTime::LogMessageTime(std::time_t timestamp, WallTime now) {
2664 std::tm t;
2665 if (FLAGS_log_utc_time)
2666 gmtime_r(&timestamp, &t);
2667 else
2668 localtime_r(&timestamp, &t);
2669 init(t, timestamp, now);
2670}
2671
2672void LogMessageTime::init(const std::tm& t, std::time_t timestamp,
2673 WallTime now) {
2674 time_struct_ = t;
2675 timestamp_ = timestamp;
2676 usecs_ = static_cast<int32>((now - timestamp) * 1000000);
2677
2678 CalcGmtOffset();
2679}
2680
2681void LogMessageTime::CalcGmtOffset() {
2682 std::tm gmt_struct;
2683 int isDst = 0;
2684 if ( FLAGS_log_utc_time ) {
2685 localtime_r(&timestamp_, &gmt_struct);
2686 isDst = gmt_struct.tm_isdst;
2687 gmt_struct = time_struct_;
2688 } else {
2689 isDst = time_struct_.tm_isdst;
2690 gmtime_r(&timestamp_, &gmt_struct);
2691 }
2692
2693 time_t gmt_sec = mktime(&gmt_struct);
2694 const long hour_secs = 3600;
2695 // If the Daylight Saving Time(isDst) is active subtract an hour from the current timestamp.
2696 gmtoffset_ = static_cast<long int>(timestamp_ - gmt_sec + (isDst ? hour_secs : 0) ) ;
2697}
2698
Austin Schuh906616c2019-01-21 20:25:11 -08002699_END_GOOGLE_NAMESPACE_