Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1 | // Copyright (c) 1999, Google Inc. |
| 2 | // All rights reserved. |
| 3 | // |
| 4 | // Redistribution and use in source and binary forms, with or without |
| 5 | // modification, are permitted provided that the following conditions are |
| 6 | // met: |
| 7 | // |
| 8 | // * Redistributions of source code must retain the above copyright |
| 9 | // notice, this list of conditions and the following disclaimer. |
| 10 | // * Redistributions in binary form must reproduce the above |
| 11 | // copyright notice, this list of conditions and the following disclaimer |
| 12 | // in the documentation and/or other materials provided with the |
| 13 | // distribution. |
| 14 | // * Neither the name of Google Inc. nor the names of its |
| 15 | // contributors may be used to endorse or promote products derived from |
| 16 | // this software without specific prior written permission. |
| 17 | // |
| 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | |
| 30 | #define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite() |
| 31 | |
| 32 | #include "utilities.h" |
| 33 | |
| 34 | #include <algorithm> |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 35 | #include <cassert> |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 36 | #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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 47 | #include <ctime> |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 48 | #include <fcntl.h> |
| 49 | #include <cstdio> |
| 50 | #include <iostream> |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 51 | #include <cstdarg> |
| 52 | #include <cstdlib> |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 53 | #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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 60 | #include <cerrno> // for errno |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 61 | #include <sstream> |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 62 | #ifdef GLOG_OS_WINDOWS |
| 63 | #include "windows/dirent.h" |
| 64 | #else |
| 65 | #include <dirent.h> // for automatic removal of old logs |
| 66 | #endif |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 67 | #include "base/commandlineflags.h" // to get the program name |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 68 | #include <glog/logging.h> |
| 69 | #include <glog/raw_logging.h> |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 70 | #include "base/googleinit.h" |
| 71 | |
| 72 | #ifdef HAVE_STACKTRACE |
| 73 | # include "stacktrace.h" |
| 74 | #endif |
| 75 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 76 | #ifdef __ANDROID__ |
| 77 | #include <android/log.h> |
| 78 | #endif |
| 79 | |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 80 | using std::string; |
| 81 | using std::vector; |
| 82 | using std::setw; |
| 83 | using std::setfill; |
| 84 | using std::hex; |
| 85 | using std::dec; |
| 86 | using std::min; |
| 87 | using std::ostream; |
| 88 | using std::ostringstream; |
| 89 | |
| 90 | using std::FILE; |
| 91 | using std::fwrite; |
| 92 | using std::fclose; |
| 93 | using std::fflush; |
| 94 | using std::fprintf; |
| 95 | using std::perror; |
| 96 | |
| 97 | #ifdef __QNX__ |
| 98 | using 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 | |
| 108 | static 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 116 | GLOG_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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 119 | GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false), |
| 120 | "log messages go to stderr instead of logfiles"); |
| 121 | GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false), |
| 122 | "log messages go to stderr in addition to logfiles"); |
| 123 | GLOG_DEFINE_bool(colorlogtostderr, false, |
| 124 | "color messages logged to stderr (if supported by terminal)"); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 125 | GLOG_DEFINE_bool(colorlogtostdout, false, |
| 126 | "color messages logged to stdout (if supported by terminal)"); |
| 127 | GLOG_DEFINE_bool(logtostdout, BoolFromEnv("GOOGLE_LOGTOSTDOUT", false), |
| 128 | "log messages go to stdout instead of logfiles"); |
| 129 | #ifdef GLOG_OS_LINUX |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 130 | GLOG_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. |
| 141 | DEFINE_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 | |
| 146 | GLOG_DEFINE_string(alsologtoemail, "", |
| 147 | "log messages go to these email addresses " |
| 148 | "in addition to logfiles"); |
| 149 | GLOG_DEFINE_bool(log_prefix, true, |
| 150 | "Prepend the log prefix to the start of each log line"); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 151 | GLOG_DEFINE_bool(log_year_in_prefix, true, |
| 152 | "Include the year in the log prefix"); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 153 | GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't " |
| 154 | "actually get logged anywhere"); |
| 155 | GLOG_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 | " ...)"); |
| 159 | GLOG_DEFINE_int32(logbufsecs, 30, |
| 160 | "Buffer log messages for at most this many seconds"); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 161 | |
| 162 | GLOG_DEFINE_int32(logcleansecs, 60 * 5, // every 5 minutes |
| 163 | "Clean overdue logs every this many seconds"); |
| 164 | |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 165 | GLOG_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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 169 | GLOG_DEFINE_string(logmailer, "", |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 170 | "Mailer used to send logging email"); |
| 171 | |
| 172 | // Compute the default value for --log_dir |
| 173 | static 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 | |
| 186 | GLOG_DEFINE_int32(logfile_mode, 0664, "Log file mode/permissions."); |
| 187 | |
| 188 | GLOG_DEFINE_string(log_dir, DefaultLogDir(), |
| 189 | "If specified, logfiles are written into this directory instead " |
| 190 | "of the default logging directory."); |
| 191 | GLOG_DEFINE_string(log_link, "", "Put additional links to the log " |
| 192 | "files in this directory"); |
| 193 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 194 | GLOG_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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 197 | |
| 198 | GLOG_DEFINE_bool(stop_logging_if_full_disk, false, |
| 199 | "Stop attempting to log to disk if the disk is full."); |
| 200 | |
| 201 | GLOG_DEFINE_string(log_backtrace_at, "", |
| 202 | "Emit a backtrace when logging at file:linenum."); |
| 203 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 204 | GLOG_DEFINE_bool(log_utc_time, false, |
| 205 | "Use UTC time for logging."); |
| 206 | |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 207 | // TODO(hamaji): consider windows |
| 208 | #define PATH_SEPARATOR '/' |
| 209 | |
| 210 | #ifndef HAVE_PREAD |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 211 | #if defined(GLOG_OS_WINDOWS) |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 212 | #include <basetsd.h> |
| 213 | #define ssize_t SSIZE_T |
| 214 | #endif |
| 215 | static 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 |
| 231 | static 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 | |
| 246 | static void GetHostName(string* hostname) { |
| 247 | #if defined(HAVE_SYS_UTSNAME_H) |
| 248 | struct utsname buf; |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 249 | if (uname(&buf) < 0) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 250 | // ensure null termination on failure |
| 251 | *buf.nodename = '\0'; |
| 252 | } |
| 253 | *hostname = buf.nodename; |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 254 | #elif defined(GLOG_OS_WINDOWS) |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 255 | 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. |
| 269 | static bool TerminalSupportsColor() { |
| 270 | bool term_supports_color = false; |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 271 | #ifdef GLOG_OS_WINDOWS |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 272 | // 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 | |
| 297 | enum GLogColor { |
| 298 | COLOR_DEFAULT, |
| 299 | COLOR_RED, |
| 300 | COLOR_GREEN, |
| 301 | COLOR_YELLOW |
| 302 | }; |
| 303 | |
| 304 | static 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 325 | #ifdef GLOG_OS_WINDOWS |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 326 | |
| 327 | // Returns the character attribute for the given color. |
| 328 | static 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. |
| 340 | static 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 350 | #endif // GLOG_OS_WINDOWS |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 351 | |
| 352 | // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0 |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 353 | static uint32 MaxLogSize() { |
| 354 | return (FLAGS_max_log_size > 0 && FLAGS_max_log_size < 4096 |
| 355 | ? FLAGS_max_log_size |
| 356 | : 1); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 357 | } |
| 358 | |
| 359 | // An arbitrary limit on the length of a single log message. This |
| 360 | // is so that streaming can be done more efficiently. |
| 361 | const size_t LogMessage::kMaxLogMessageLen = 30000; |
| 362 | |
| 363 | struct 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 378 | 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. |
| 396 | static Mutex log_mutex; |
| 397 | |
| 398 | // Number of messages sent at each severity. Under log_mutex. |
| 399 | int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0}; |
| 400 | |
| 401 | // Globally disable log writing (if disk is full) |
| 402 | static bool stop_writing = false; |
| 403 | |
| 404 | const char*const LogSeverityNames[NUM_SEVERITIES] = { |
| 405 | "INFO", "WARNING", "ERROR", "FATAL" |
| 406 | }; |
| 407 | |
| 408 | // Has the user called SetExitOnDFatal(true)? |
| 409 | static bool exit_on_dfatal = true; |
| 410 | |
| 411 | const char* GetLogSeverityName(LogSeverity severity) { |
| 412 | return LogSeverityNames[severity]; |
| 413 | } |
| 414 | |
| 415 | static bool SendEmailInternal(const char*dest, const char *subject, |
| 416 | const char*body, bool use_logging); |
| 417 | |
| 418 | base::Logger::~Logger() { |
| 419 | } |
| 420 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 421 | #ifdef GLOG_CUSTOM_PREFIX_SUPPORT |
| 422 | namespace { |
| 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 430 | namespace { |
| 431 | |
| 432 | // Encapsulates all file-system related state |
| 433 | class 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 441 | size_t message_len); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 442 | |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 478 | WallTime start_time_; |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 479 | |
| 480 | // Actually create a logfile using the value of base_filename_ and the |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 481 | // optional argument time_pid_string |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 482 | // REQUIRES: lock_ is held |
| 483 | bool CreateLogfile(const string& time_pid_string); |
| 484 | }; |
| 485 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 486 | // Encapsulate all log cleaner related states |
| 487 | class 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 | |
| 520 | LogCleaner log_cleaner; |
| 521 | |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 522 | } // namespace |
| 523 | |
| 524 | class 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 560 | ~LogDestination(); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 561 | |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 565 | size_t message_len, size_t prefix_len); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 566 | |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 584 | static void LogToSinks(LogSeverity severity, const char* full_filename, |
| 585 | const char* base_filename, int line, |
| 586 | const LogMessageTime& logmsgtime, const char* message, |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 587 | 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. |
| 617 | LogSeverity LogDestination::email_logging_severity_ = 99999; |
| 618 | |
| 619 | string LogDestination::addresses_; |
| 620 | string LogDestination::hostname_; |
| 621 | |
| 622 | vector<LogSink*>* LogDestination::sinks_ = NULL; |
| 623 | Mutex LogDestination::sink_mutex_; |
| 624 | bool LogDestination::terminal_supports_color_ = TerminalSupportsColor(); |
| 625 | |
| 626 | /* static */ |
| 627 | const string& LogDestination::hostname() { |
| 628 | if (hostname_.empty()) { |
| 629 | GetHostName(&hostname_); |
| 630 | if (hostname_.empty()) { |
| 631 | hostname_ = "(unknown)"; |
| 632 | } |
| 633 | } |
| 634 | return hostname_; |
| 635 | } |
| 636 | |
| 637 | LogDestination::LogDestination(LogSeverity severity, |
| 638 | const char* base_filename) |
| 639 | : fileobject_(severity, base_filename), |
| 640 | logger_(&fileobject_) { |
| 641 | } |
| 642 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 643 | LogDestination::~LogDestination() { |
| 644 | if (logger_ && logger_ != &fileobject_) { |
| 645 | // Delete user-specified logger set via SetLogger(). |
| 646 | delete logger_; |
| 647 | } |
| 648 | } |
| 649 | |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 650 | inline 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 | |
| 663 | inline 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 | |
| 675 | inline 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 | |
| 684 | inline 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 | |
| 692 | inline 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 | |
| 700 | inline 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 706 | sinks_->erase(std::remove(sinks_->begin(), sinks_->end(), destination), sinks_->end()); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 707 | } |
| 708 | } |
| 709 | |
| 710 | inline 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 | |
| 719 | inline 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 | |
| 727 | inline 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 | |
| 736 | inline 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 746 | static 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 754 | |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 758 | fwrite(message, len, 1, output); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 759 | return; |
| 760 | } |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 761 | #ifdef GLOG_OS_WINDOWS |
| 762 | const HANDLE output_handle = |
| 763 | GetStdHandle(is_stdout ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 764 | |
| 765 | // Gets the current text color. |
| 766 | CONSOLE_SCREEN_BUFFER_INFO buffer_info; |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 767 | GetConsoleScreenBufferInfo(output_handle, &buffer_info); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 768 | 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 773 | fflush(output); |
| 774 | SetConsoleTextAttribute(output_handle, |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 775 | GetColorAttribute(color) | FOREGROUND_INTENSITY); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 776 | fwrite(message, len, 1, output); |
| 777 | fflush(output); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 778 | // Restores the text color. |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 779 | SetConsoleTextAttribute(output_handle, old_color_attrs); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 780 | #else |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 781 | 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 | |
| 787 | static 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 | |
| 798 | static void ColoredWriteToStderr(LogSeverity severity, const char* message, |
| 799 | size_t len) { |
| 800 | ColoredWriteToStderrOrStdout(stderr, severity, message, len); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 801 | } |
| 802 | |
| 803 | static 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 | |
| 809 | inline void LogDestination::MaybeLogToStderr(LogSeverity severity, |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 810 | const char* message, size_t message_len, size_t prefix_len) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 811 | if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 812 | ColoredWriteToStderr(severity, message, message_len); |
| 813 | #ifdef GLOG_OS_WINDOWS |
| 814 | (void) prefix_len; |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 815 | // On Windows, also output to the debugger |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 816 | ::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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 830 | #endif |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | |
| 835 | inline 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 | |
| 861 | inline 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 | |
| 870 | inline void LogDestination::LogToAllLogfiles(LogSeverity severity, |
| 871 | time_t timestamp, |
| 872 | const char* message, |
| 873 | size_t len) { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 874 | 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 877 | ColoredWriteToStderr(severity, message, len); |
| 878 | } else { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 879 | for (int i = severity; i >= 0; --i) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 880 | LogDestination::MaybeLogToLogfile(i, timestamp, message, len); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 881 | } |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 882 | } |
| 883 | } |
| 884 | |
| 885 | inline void LogDestination::LogToSinks(LogSeverity severity, |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 886 | const char* full_filename, |
| 887 | const char* base_filename, int line, |
| 888 | const LogMessageTime& logmsgtime, |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 889 | const char* message, |
| 890 | size_t message_len) { |
| 891 | ReaderMutexLock l(&sink_mutex_); |
| 892 | if (sinks_) { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 893 | for (size_t i = sinks_->size(); i-- > 0; ) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 894 | (*sinks_)[i]->send(severity, full_filename, base_filename, |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 895 | line, logmsgtime, message, message_len); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 896 | } |
| 897 | } |
| 898 | } |
| 899 | |
| 900 | inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) { |
| 901 | ReaderMutexLock l(&sink_mutex_); |
| 902 | if (sinks_) { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 903 | for (size_t i = sinks_->size(); i-- > 0; ) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 904 | (*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 | |
| 915 | LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES]; |
| 916 | |
| 917 | inline 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 | |
| 925 | void 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 | |
| 935 | namespace { |
| 936 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 937 | std::string g_application_fingerprint; |
| 938 | |
| 939 | } // namespace |
| 940 | |
| 941 | void SetApplicationFingerprint(const std::string& fingerprint) { |
| 942 | g_application_fingerprint = fingerprint; |
| 943 | } |
| 944 | |
| 945 | namespace { |
| 946 | |
| 947 | // Directory delimiter; Windows supports both forward slashes and backslashes |
| 948 | #ifdef GLOG_OS_WINDOWS |
| 949 | const char possible_dir_delim[] = {'\\', '/'}; |
| 950 | #else |
| 951 | const char possible_dir_delim[] = {'/'}; |
| 952 | #endif |
| 953 | |
| 954 | string 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 966 | LogFileObject::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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 978 | next_flush_time_(0), |
| 979 | start_time_(WallTime_Now()) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 980 | assert(severity >= 0); |
| 981 | assert(severity < NUM_SEVERITIES); |
| 982 | } |
| 983 | |
| 984 | LogFileObject::~LogFileObject() { |
| 985 | MutexLock l(&lock_); |
| 986 | if (file_ != NULL) { |
| 987 | fclose(file_); |
| 988 | file_ = NULL; |
| 989 | } |
| 990 | } |
| 991 | |
| 992 | void 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 | |
| 1006 | void 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 | |
| 1019 | void LogFileObject::SetSymlinkBasename(const char* symlink_basename) { |
| 1020 | MutexLock l(&lock_); |
| 1021 | symlink_basename_ = symlink_basename; |
| 1022 | } |
| 1023 | |
| 1024 | void LogFileObject::Flush() { |
| 1025 | MutexLock l(&lock_); |
| 1026 | FlushUnlocked(); |
| 1027 | } |
| 1028 | |
| 1029 | void 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 | |
| 1040 | bool LogFileObject::CreateLogfile(const string& time_pid_string) { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1041 | 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1046 | const char* filename = string_filename.c_str(); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1047 | //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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1054 | 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1058 | |
| 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1080 | #endif |
| 1081 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1082 | //fdopen in append mode so if the file exists it will fseek to the end |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1083 | file_ = fdopen(fd, "a"); // Make a FILE*. |
| 1084 | if (file_ == NULL) { // Man, we're screwed! |
| 1085 | close(fd); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1086 | 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1089 | return false; |
| 1090 | } |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1091 | #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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1100 | // 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1111 | if ( slash ) linkpath = string(filename, static_cast<size_t>(slash-filename+1)); // get dirname |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1112 | linkpath += linkname; |
| 1113 | unlink(linkpath.c_str()); // delete old one if it exists |
| 1114 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1115 | #if defined(GLOG_OS_WINDOWS) |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1116 | // 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 | |
| 1141 | void LogFileObject::Write(bool force_flush, |
| 1142 | time_t timestamp, |
| 1143 | const char* message, |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1144 | size_t message_len) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1145 | 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1152 | if (file_length_ >> 20U >= MaxLogSize() || PidHasChanged()) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1153 | if (file_ != NULL) fclose(file_); |
| 1154 | file_ = NULL; |
| 1155 | file_length_ = bytes_since_flush_ = dropped_mem_length_ = 0; |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1156 | rollover_attempt_ = kRolloverAttemptFrequency - 1; |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1157 | } |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1168 | if (FLAGS_log_utc_time) { |
| 1169 | gmtime_r(×tamp, &tm_time); |
| 1170 | } else { |
| 1171 | localtime_r(×tamp, &tm_time); |
| 1172 | } |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1173 | |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1256 | << setw(2) << tm_time.tm_sec << (FLAGS_log_utc_time ? " UTC\n" : "\n") |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1257 | << "Running on machine: " |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1258 | << 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1269 | << "threadid file:line] msg" << '\n'; |
| 1270 | const string& file_header_string = file_header_stream.str(); |
| 1271 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1272 | const size_t header_len = file_header_string.size(); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1273 | 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1296 | if (CycleClock_Now() >= next_flush_time_) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1297 | stop_writing = false; // check to see if disk has free space. |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1298 | } |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1299 | 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1308 | #ifdef GLOG_OS_LINUX |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1309 | // Only consider files >= 3MiB |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1310 | if (FLAGS_drop_log_memory && file_length_ >= (3U << 20U)) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1311 | // 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1313 | uint32 total_drop_length = |
| 1314 | (file_length_ & ~((1U << 20U) - 1U)) - (1U << 20U); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1315 | uint32 this_drop_length = total_drop_length - dropped_mem_length_; |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1316 | if (this_drop_length >= (2U << 20U)) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1317 | // Only advise when >= 2MiB to drop |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1318 | # 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1324 | POSIX_FADV_DONTNEED); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1325 | # endif |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1326 | dropped_mem_length_ = total_drop_length; |
| 1327 | } |
| 1328 | } |
| 1329 | #endif |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1330 | |
| 1331 | // Remove old logs |
| 1332 | if (log_cleaner.enabled()) { |
| 1333 | log_cleaner.Run(base_filename_selected_, |
| 1334 | base_filename_, |
| 1335 | filename_extension_); |
| 1336 | } |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1337 | } |
| 1338 | } |
| 1339 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1340 | LogCleaner::LogCleaner() : enabled_(false), overdue_days_(7), next_cleanup_time_(0) {} |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1341 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1342 | void LogCleaner::Enable(unsigned int overdue_days) { |
| 1343 | enabled_ = true; |
| 1344 | overdue_days_ = overdue_days; |
| 1345 | } |
| 1346 | |
| 1347 | void LogCleaner::Disable() { |
| 1348 | enabled_ = false; |
| 1349 | } |
| 1350 | |
| 1351 | void LogCleaner::UpdateCleanUpTime() { |
| 1352 | const int64 next = (FLAGS_logcleansecs |
| 1353 | * 1000000); // in usec |
| 1354 | next_cleanup_time_ = CycleClock_Now() + UsecToCycles(next); |
| 1355 | } |
| 1356 | |
| 1357 | void 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 | |
| 1395 | vector<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 | |
| 1432 | bool 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 | |
| 1511 | bool 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1528 | |
| 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. |
| 1535 | static Mutex fatal_msg_lock; |
| 1536 | static CrashReason crash_reason; |
| 1537 | static bool fatal_msg_exclusive = true; |
| 1538 | static LogMessage::LogMessageData fatal_msg_data_exclusive; |
| 1539 | static 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). |
| 1545 | static GLOG_THREAD_LOCAL_STORAGE bool thread_data_available = true; |
| 1546 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1547 | #if defined(HAVE_ALIGNED_STORAGE) && __cplusplus >= 201103L |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1548 | static GLOG_THREAD_LOCAL_STORAGE |
| 1549 | std::aligned_storage<sizeof(LogMessage::LogMessageData), |
| 1550 | alignof(LogMessage::LogMessageData)>::type thread_msg_data; |
| 1551 | #else |
| 1552 | static 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 | |
| 1557 | LogMessage::LogMessageData::LogMessageData() |
| 1558 | : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) { |
| 1559 | } |
| 1560 | |
| 1561 | LogMessage::LogMessage(const char* file, int line, LogSeverity severity, |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1562 | int64 ctr, void (LogMessage::*send_method)()) |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1563 | : allocated_(NULL) { |
| 1564 | Init(file, line, severity, send_method); |
| 1565 | data_->stream_.set_ctr(ctr); |
| 1566 | } |
| 1567 | |
| 1568 | LogMessage::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 | |
| 1575 | LogMessage::LogMessage(const char* file, int line) |
| 1576 | : allocated_(NULL) { |
| 1577 | Init(file, line, GLOG_INFO, &LogMessage::SendToLog); |
| 1578 | } |
| 1579 | |
| 1580 | LogMessage::LogMessage(const char* file, int line, LogSeverity severity) |
| 1581 | : allocated_(NULL) { |
| 1582 | Init(file, line, severity, &LogMessage::SendToLog); |
| 1583 | } |
| 1584 | |
| 1585 | LogMessage::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 | |
| 1593 | LogMessage::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 | |
| 1600 | LogMessage::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 | |
| 1607 | void 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1648 | 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1655 | time_t timestamp_now = static_cast<time_t>(now); |
| 1656 | logmsgtime_ = LogMessageTime(timestamp_now, now); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1657 | |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1665 | // I20201018 160715 f5d4fbb0 logging.cc:1153] |
| 1666 | // (log level, GMT year, month, date, time, thread_id, file basename, line) |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1667 | // We exclude the thread_id for the default thread. |
| 1668 | if (FLAGS_log_prefix && (line != kNoLogPrefix)) { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1669 | 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1704 | } |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1711 | if (FLAGS_log_backtrace_at == fileline) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1712 | string stacktrace; |
| 1713 | DumpStackTraceToString(&stacktrace); |
| 1714 | stream() << " (stacktrace:\n" << stacktrace << ") "; |
| 1715 | } |
| 1716 | #endif |
| 1717 | } |
| 1718 | } |
| 1719 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1720 | const LogMessageTime& LogMessage::getLogMessageTime() const { |
| 1721 | return logmsgtime_; |
| 1722 | } |
| 1723 | |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1724 | LogMessage::~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 | |
| 1739 | int LogMessage::preserved_errno() const { |
| 1740 | return data_->preserved_errno_; |
| 1741 | } |
| 1742 | |
| 1743 | ostream& 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. |
| 1749 | void LogMessage::Flush() { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1750 | if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1751 | return; |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1752 | } |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1753 | |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1772 | data_->message_text_[data_->num_chars_to_log_] = '\0'; |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1773 | |
| 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. |
| 1806 | static time_t fatal_time; |
| 1807 | static char fatal_message[256]; |
| 1808 | |
| 1809 | void ReprintFatalMessage() { |
| 1810 | if (fatal_message[0]) { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1811 | const size_t n = strlen(fatal_message); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1812 | 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). |
| 1821 | void 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1841 | 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1849 | |
| 1850 | // this could be protected by a flag if necessary. |
| 1851 | LogDestination::LogToSinks(data_->severity_, |
| 1852 | data_->fullname_, data_->basename_, |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1853 | data_->line_, logmsgtime_, |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1854 | data_->message_text_ + data_->num_prefix_chars_, |
| 1855 | (data_->num_chars_to_log_ - |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1856 | data_->num_prefix_chars_ - 1) ); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1857 | } else { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1858 | // log this message to all log files of severity <= severity_ |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1859 | LogDestination::LogToAllLogfiles(data_->severity_, logmsgtime_.timestamp(), |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1860 | data_->message_text_, |
| 1861 | data_->num_chars_to_log_); |
| 1862 | |
| 1863 | LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_, |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1864 | data_->num_chars_to_log_, |
| 1865 | data_->num_prefix_chars_); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1866 | LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_, |
| 1867 | data_->num_chars_to_log_); |
| 1868 | LogDestination::LogToSinks(data_->severity_, |
| 1869 | data_->fullname_, data_->basename_, |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1870 | data_->line_, logmsgtime_, |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1871 | data_->message_text_ + data_->num_prefix_chars_, |
| 1872 | (data_->num_chars_to_log_ |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1873 | - data_->num_prefix_chars_ - 1) ); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1874 | // 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1888 | const size_t copy = min(data_->num_chars_to_log_, |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1889 | sizeof(fatal_message)-1); |
| 1890 | memcpy(fatal_message, data_->message_text_, copy); |
| 1891 | fatal_message[copy] = '\0'; |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1892 | fatal_time = logmsgtime_.timestamp(); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1893 | } |
| 1894 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1895 | if (!FLAGS_logtostderr && !FLAGS_logtostdout) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1896 | for (int i = 0; i < NUM_SEVERITIES; ++i) { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1897 | if (LogDestination::log_destinations_[i]) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1898 | LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1899 | } |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1900 | } |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1915 | #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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1921 | Fail(); |
| 1922 | } |
| 1923 | } |
| 1924 | |
| 1925 | void 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1939 | GLOG_EXPORT logging_fail_func_t g_logging_fail_func = |
| 1940 | reinterpret_cast<logging_fail_func_t>(&abort); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1941 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1942 | void InstallFailureFunction(logging_fail_func_t fail_func) { |
| 1943 | g_logging_fail_func = fail_func; |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1944 | } |
| 1945 | |
| 1946 | void LogMessage::Fail() { |
| 1947 | g_logging_fail_func(); |
| 1948 | } |
| 1949 | |
| 1950 | // L >= log_mutex (callers must hold the log_mutex). |
| 1951 | void 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1956 | data_->line_, logmsgtime_, |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1957 | data_->message_text_ + data_->num_prefix_chars_, |
| 1958 | (data_->num_chars_to_log_ - |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1959 | data_->num_prefix_chars_ - 1) ); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1960 | } |
| 1961 | } |
| 1962 | |
| 1963 | // L >= log_mutex (callers must hold the log_mutex). |
| 1964 | void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { |
| 1965 | SendToSink(); |
| 1966 | SendToLog(); |
| 1967 | } |
| 1968 | |
| 1969 | // L >= log_mutex (callers must hold the log_mutex). |
| 1970 | void 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1976 | size_t len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1977 | data_->outvec_->push_back(string(start, len)); |
| 1978 | } else { |
| 1979 | SendToLog(); |
| 1980 | } |
| 1981 | } |
| 1982 | |
| 1983 | void 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 1989 | size_t len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 1990 | data_->message_->assign(start, len); |
| 1991 | } |
| 1992 | SendToLog(); |
| 1993 | } |
| 1994 | |
| 1995 | // L >= log_mutex (callers must hold the log_mutex). |
| 1996 | void 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 | |
| 2018 | base::Logger* base::GetLogger(LogSeverity severity) { |
| 2019 | MutexLock l(&log_mutex); |
| 2020 | return LogDestination::log_destination(severity)->logger_; |
| 2021 | } |
| 2022 | |
| 2023 | void 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_. |
| 2029 | int64 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. |
| 2036 | ostream& 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 | |
| 2048 | ErrnoLogMessage::ErrnoLogMessage(const char* file, int line, |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2049 | LogSeverity severity, int64 ctr, |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2050 | void (LogMessage::*send_method)()) |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2051 | : LogMessage(file, line, severity, ctr, send_method) {} |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2052 | |
| 2053 | ErrnoLogMessage::~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 | |
| 2060 | void FlushLogFiles(LogSeverity min_severity) { |
| 2061 | LogDestination::FlushLogFiles(min_severity); |
| 2062 | } |
| 2063 | |
| 2064 | void FlushLogFilesUnsafe(LogSeverity min_severity) { |
| 2065 | LogDestination::FlushLogFilesUnsafe(min_severity); |
| 2066 | } |
| 2067 | |
| 2068 | void SetLogDestination(LogSeverity severity, const char* base_filename) { |
| 2069 | LogDestination::SetLogDestination(severity, base_filename); |
| 2070 | } |
| 2071 | |
| 2072 | void SetLogSymlink(LogSeverity severity, const char* symlink_basename) { |
| 2073 | LogDestination::SetLogSymlink(severity, symlink_basename); |
| 2074 | } |
| 2075 | |
| 2076 | LogSink::~LogSink() { |
| 2077 | } |
| 2078 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2079 | void 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 | |
| 2099 | void 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2111 | void LogSink::WaitTillSent() { |
| 2112 | // noop default |
| 2113 | } |
| 2114 | |
| 2115 | string LogSink::ToString(LogSeverity severity, const char* file, int line, |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2116 | const LogMessageTime& logmsgtime, const char* message, |
| 2117 | size_t message_len) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2118 | ostringstream stream(string(message, message_len)); |
| 2119 | stream.fill('0'); |
| 2120 | |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2121 | stream << LogSeverityNames[severity][0] |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2122 | << setw(4) << 1900 + logmsgtime.year() |
| 2123 | << setw(2) << 1 + logmsgtime.month() |
| 2124 | << setw(2) << logmsgtime.day() |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2125 | << ' ' |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2126 | << setw(2) << logmsgtime.hour() << ':' |
| 2127 | << setw(2) << logmsgtime.min() << ':' |
| 2128 | << setw(2) << logmsgtime.sec() << '.' |
| 2129 | << setw(6) << logmsgtime.usec() |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2130 | << ' ' |
| 2131 | << setfill(' ') << setw(5) << GetTID() << setfill('0') |
| 2132 | << ' ' |
| 2133 | << file << ':' << line << "] "; |
| 2134 | |
| 2135 | stream << string(message, message_len); |
| 2136 | return stream.str(); |
| 2137 | } |
| 2138 | |
| 2139 | void AddLogSink(LogSink *destination) { |
| 2140 | LogDestination::AddLogSink(destination); |
| 2141 | } |
| 2142 | |
| 2143 | void RemoveLogSink(LogSink *destination) { |
| 2144 | LogDestination::RemoveLogSink(destination); |
| 2145 | } |
| 2146 | |
| 2147 | void SetLogFilenameExtension(const char* ext) { |
| 2148 | LogDestination::SetLogFilenameExtension(ext); |
| 2149 | } |
| 2150 | |
| 2151 | void SetStderrLogging(LogSeverity min_severity) { |
| 2152 | LogDestination::SetStderrLogging(min_severity); |
| 2153 | } |
| 2154 | |
| 2155 | void SetEmailLogging(LogSeverity min_severity, const char* addresses) { |
| 2156 | LogDestination::SetEmailLogging(min_severity, addresses); |
| 2157 | } |
| 2158 | |
| 2159 | void LogToStderr() { |
| 2160 | LogDestination::LogToStderr(); |
| 2161 | } |
| 2162 | |
| 2163 | namespace base { |
| 2164 | namespace internal { |
| 2165 | |
| 2166 | bool GetExitOnDFatal(); |
| 2167 | bool 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. |
| 2182 | void SetExitOnDFatal(bool value); |
| 2183 | void SetExitOnDFatal(bool value) { |
| 2184 | MutexLock l(&log_mutex); |
| 2185 | exit_on_dfatal = value; |
| 2186 | } |
| 2187 | |
| 2188 | } // namespace internal |
| 2189 | } // namespace base |
| 2190 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2191 | #ifndef GLOG_OS_EMSCRIPTEN |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2192 | // Shell-escaping as we need to shell out ot /bin/mail. |
| 2193 | static const char kDontNeedShellEscapeChars[] = |
| 2194 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 2195 | "abcdefghijklmnopqrstuvwxyz" |
| 2196 | "0123456789+-_.=/:,@"; |
| 2197 | |
| 2198 | static 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2226 | #endif |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2227 | |
| 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. |
| 2231 | static bool SendEmailInternal(const char*dest, const char *subject, |
| 2232 | const char*body, bool use_logging) { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2233 | #ifndef GLOG_OS_EMSCRIPTEN |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2234 | 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2243 | string logmailer = FLAGS_logmailer; |
| 2244 | if (logmailer.empty()) { |
| 2245 | logmailer = "/bin/mail"; |
| 2246 | } |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2247 | string cmd = |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2248 | logmailer + " -s" + |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2249 | ShellEscape(subject) + " " + ShellEscape(dest); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2250 | if (use_logging) { |
| 2251 | VLOG(4) << "Mailing command: " << cmd; |
| 2252 | } |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2253 | |
| 2254 | FILE* pipe = popen(cmd.c_str(), "w"); |
| 2255 | if (pipe != NULL) { |
| 2256 | // Add the body if we have one |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2257 | if (body) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2258 | fwrite(body, sizeof(char), strlen(body), pipe); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2259 | } |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2260 | 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2279 | #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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2286 | return false; |
| 2287 | } |
| 2288 | |
| 2289 | bool SendEmail(const char*dest, const char *subject, const char*body){ |
| 2290 | return SendEmailInternal(dest, subject, body, true); |
| 2291 | } |
| 2292 | |
| 2293 | static void GetTempDirectories(vector<string>* list) { |
| 2294 | list->clear(); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2295 | #ifdef GLOG_OS_WINDOWS |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2296 | // 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 | |
| 2342 | static vector<string>* logging_directories_list; |
| 2343 | |
| 2344 | const 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2351 | logging_directories_list->push_back(FLAGS_log_dir); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2352 | } else { |
| 2353 | GetTempDirectories(logging_directories_list); |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2354 | #ifdef GLOG_OS_WINDOWS |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2355 | 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 | |
| 2367 | void 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 | |
| 2374 | void 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2388 | void TruncateLogFile(const char *path, uint64 limit, uint64 keep) { |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2389 | #ifdef HAVE_UNISTD_H |
| 2390 | struct stat statbuf; |
| 2391 | const int kCopyBlockSize = 8 << 10; |
| 2392 | char copybuf[kCopyBlockSize]; |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2393 | off_t read_offset, write_offset; |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2394 | // 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2397 | #ifdef GLOG_OS_LINUX |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2398 | 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2429 | 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2431 | |
| 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2436 | read_offset = statbuf.st_size - static_cast<off_t>(keep); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2437 | write_offset = 0; |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2438 | ssize_t bytesin, bytesout; |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2439 | while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2440 | bytesout = pwrite(fd, copybuf, static_cast<size_t>(bytesin), write_offset); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2441 | 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2464 | } |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2465 | |
| 2466 | void TruncateStdoutStderr() { |
| 2467 | #ifdef HAVE_UNISTD_H |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2468 | uint64 limit = MaxLogSize() << 20U; |
| 2469 | uint64 keep = 1U << 20U; |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2470 | 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 | } |
| 2492 | DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true) |
| 2493 | DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false) |
| 2494 | DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true) |
| 2495 | DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false) |
| 2496 | #undef DEFINE_CHECK_STROP_IMPL |
| 2497 | |
| 2498 | int 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 Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2536 | #if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || defined(GLOG_OS_OPENBSD) |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2537 | 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 | |
| 2548 | string 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 | |
| 2557 | LogMessageFatal::LogMessageFatal(const char* file, int line) : |
| 2558 | LogMessage(file, line, GLOG_FATAL) {} |
| 2559 | |
| 2560 | LogMessageFatal::LogMessageFatal(const char* file, int line, |
| 2561 | const CheckOpString& result) : |
| 2562 | LogMessage(file, line, result) {} |
| 2563 | |
| 2564 | LogMessageFatal::~LogMessageFatal() { |
| 2565 | Flush(); |
| 2566 | LogMessage::Fail(); |
| 2567 | } |
| 2568 | |
| 2569 | namespace base { |
| 2570 | |
| 2571 | CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext) |
| 2572 | : stream_(new ostringstream) { |
| 2573 | *stream_ << exprtext << " ("; |
| 2574 | } |
| 2575 | |
| 2576 | CheckOpMessageBuilder::~CheckOpMessageBuilder() { |
| 2577 | delete stream_; |
| 2578 | } |
| 2579 | |
| 2580 | ostream* CheckOpMessageBuilder::ForVar2() { |
| 2581 | *stream_ << " vs. "; |
| 2582 | return stream_; |
| 2583 | } |
| 2584 | |
| 2585 | string* CheckOpMessageBuilder::NewString() { |
| 2586 | *stream_ << ")"; |
| 2587 | return new string(stream_->str()); |
| 2588 | } |
| 2589 | |
| 2590 | } // namespace base |
| 2591 | |
| 2592 | template <> |
| 2593 | void MakeCheckOpValueString(std::ostream* os, const char& v) { |
| 2594 | if (v >= 32 && v <= 126) { |
| 2595 | (*os) << "'" << v << "'"; |
| 2596 | } else { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2597 | (*os) << "char value " << static_cast<short>(v); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2598 | } |
| 2599 | } |
| 2600 | |
| 2601 | template <> |
| 2602 | void MakeCheckOpValueString(std::ostream* os, const signed char& v) { |
| 2603 | if (v >= 32 && v <= 126) { |
| 2604 | (*os) << "'" << v << "'"; |
| 2605 | } else { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2606 | (*os) << "signed char value " << static_cast<short>(v); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2607 | } |
| 2608 | } |
| 2609 | |
| 2610 | template <> |
| 2611 | void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) { |
| 2612 | if (v >= 32 && v <= 126) { |
| 2613 | (*os) << "'" << v << "'"; |
| 2614 | } else { |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2615 | (*os) << "unsigned char value " << static_cast<unsigned short>(v); |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2616 | } |
| 2617 | } |
| 2618 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2619 | #if defined(HAVE_CXX11_NULLPTR_T) && __cplusplus >= 201103L |
| 2620 | template <> |
| 2621 | void MakeCheckOpValueString(std::ostream* os, const std::nullptr_t& /*v*/) { |
| 2622 | (*os) << "nullptr"; |
| 2623 | } |
| 2624 | #endif // defined(HAVE_CXX11_NULLPTR_T) |
| 2625 | |
Austin Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2626 | void InitGoogleLogging(const char* argv0) { |
| 2627 | glog_internal_namespace_::InitGoogleLoggingUtilities(argv0); |
| 2628 | } |
| 2629 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2630 | #ifdef GLOG_CUSTOM_PREFIX_SUPPORT |
| 2631 | void 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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2640 | void ShutdownGoogleLogging() { |
| 2641 | glog_internal_namespace_::ShutdownGoogleLoggingUtilities(); |
| 2642 | LogDestination::DeleteLogDestinations(); |
| 2643 | delete logging_directories_list; |
| 2644 | logging_directories_list = NULL; |
| 2645 | } |
| 2646 | |
James Kuszmaul | ba0ac1a | 2022-08-12 16:29:30 -0700 | [diff] [blame^] | 2647 | void EnableLogCleaner(unsigned int overdue_days) { |
| 2648 | log_cleaner.Enable(overdue_days); |
| 2649 | } |
| 2650 | |
| 2651 | void DisableLogCleaner() { |
| 2652 | log_cleaner.Disable(); |
| 2653 | } |
| 2654 | |
| 2655 | LogMessageTime::LogMessageTime() |
| 2656 | : time_struct_(), timestamp_(0), usecs_(0), gmtoffset_(0) {} |
| 2657 | |
| 2658 | LogMessageTime::LogMessageTime(std::tm t) { |
| 2659 | std::time_t timestamp = std::mktime(&t); |
| 2660 | init(t, timestamp, 0); |
| 2661 | } |
| 2662 | |
| 2663 | LogMessageTime::LogMessageTime(std::time_t timestamp, WallTime now) { |
| 2664 | std::tm t; |
| 2665 | if (FLAGS_log_utc_time) |
| 2666 | gmtime_r(×tamp, &t); |
| 2667 | else |
| 2668 | localtime_r(×tamp, &t); |
| 2669 | init(t, timestamp, now); |
| 2670 | } |
| 2671 | |
| 2672 | void 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 | |
| 2681 | void LogMessageTime::CalcGmtOffset() { |
| 2682 | std::tm gmt_struct; |
| 2683 | int isDst = 0; |
| 2684 | if ( FLAGS_log_utc_time ) { |
| 2685 | localtime_r(×tamp_, &gmt_struct); |
| 2686 | isDst = gmt_struct.tm_isdst; |
| 2687 | gmt_struct = time_struct_; |
| 2688 | } else { |
| 2689 | isDst = time_struct_.tm_isdst; |
| 2690 | gmtime_r(×tamp_, &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 Schuh | 906616c | 2019-01-21 20:25:11 -0800 | [diff] [blame] | 2699 | _END_GOOGLE_NAMESPACE_ |