env_logger.h 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. //
  10. // Logger implementation that uses custom Env object for logging.
  11. #pragma once
  12. #include <time.h>
  13. #include <atomic>
  14. #include <memory>
  15. #include "port/sys_time.h"
  16. #include "file/writable_file_writer.h"
  17. #include "monitoring/iostats_context_imp.h"
  18. #include "rocksdb/env.h"
  19. #include "rocksdb/slice.h"
  20. #include "test_util/sync_point.h"
  21. #include "util/mutexlock.h"
  22. namespace ROCKSDB_NAMESPACE {
  23. class EnvLogger : public Logger {
  24. public:
  25. EnvLogger(std::unique_ptr<FSWritableFile>&& writable_file,
  26. const std::string& fname, const EnvOptions& options, Env* env,
  27. InfoLogLevel log_level = InfoLogLevel::ERROR_LEVEL)
  28. : Logger(log_level),
  29. file_(std::move(writable_file), fname, options, env),
  30. last_flush_micros_(0),
  31. env_(env),
  32. flush_pending_(false) {}
  33. ~EnvLogger() {
  34. if (!closed_) {
  35. closed_ = true;
  36. CloseHelper();
  37. }
  38. }
  39. private:
  40. void FlushLocked() {
  41. mutex_.AssertHeld();
  42. if (flush_pending_) {
  43. flush_pending_ = false;
  44. file_.Flush();
  45. }
  46. last_flush_micros_ = env_->NowMicros();
  47. }
  48. void Flush() override {
  49. TEST_SYNC_POINT("EnvLogger::Flush:Begin1");
  50. TEST_SYNC_POINT("EnvLogger::Flush:Begin2");
  51. MutexLock l(&mutex_);
  52. FlushLocked();
  53. }
  54. Status CloseImpl() override { return CloseHelper(); }
  55. Status CloseHelper() {
  56. mutex_.Lock();
  57. const auto close_status = file_.Close();
  58. mutex_.Unlock();
  59. if (close_status.ok()) {
  60. return close_status;
  61. }
  62. return Status::IOError("Close of log file failed with error:" +
  63. (close_status.getState()
  64. ? std::string(close_status.getState())
  65. : std::string()));
  66. }
  67. using Logger::Logv;
  68. void Logv(const char* format, va_list ap) override {
  69. IOSTATS_TIMER_GUARD(logger_nanos);
  70. const uint64_t thread_id = env_->GetThreadID();
  71. // We try twice: the first time with a fixed-size stack allocated buffer,
  72. // and the second time with a much larger dynamically allocated buffer.
  73. char buffer[500];
  74. for (int iter = 0; iter < 2; iter++) {
  75. char* base;
  76. int bufsize;
  77. if (iter == 0) {
  78. bufsize = sizeof(buffer);
  79. base = buffer;
  80. } else {
  81. bufsize = 65536;
  82. base = new char[bufsize];
  83. }
  84. char* p = base;
  85. char* limit = base + bufsize;
  86. struct timeval now_tv;
  87. gettimeofday(&now_tv, nullptr);
  88. const time_t seconds = now_tv.tv_sec;
  89. struct tm t;
  90. localtime_r(&seconds, &t);
  91. p += snprintf(p, limit - p, "%04d/%02d/%02d-%02d:%02d:%02d.%06d %llx ",
  92. t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour,
  93. t.tm_min, t.tm_sec, static_cast<int>(now_tv.tv_usec),
  94. static_cast<long long unsigned int>(thread_id));
  95. // Print the message
  96. if (p < limit) {
  97. va_list backup_ap;
  98. va_copy(backup_ap, ap);
  99. p += vsnprintf(p, limit - p, format, backup_ap);
  100. va_end(backup_ap);
  101. }
  102. // Truncate to available space if necessary
  103. if (p >= limit) {
  104. if (iter == 0) {
  105. continue; // Try again with larger buffer
  106. } else {
  107. p = limit - 1;
  108. }
  109. }
  110. // Add newline if necessary
  111. if (p == base || p[-1] != '\n') {
  112. *p++ = '\n';
  113. }
  114. assert(p <= limit);
  115. mutex_.Lock();
  116. // We will ignore any error returned by Append().
  117. file_.Append(Slice(base, p - base));
  118. flush_pending_ = true;
  119. const uint64_t now_micros = env_->NowMicros();
  120. if (now_micros - last_flush_micros_ >= flush_every_seconds_ * 1000000) {
  121. FlushLocked();
  122. }
  123. mutex_.Unlock();
  124. if (base != buffer) {
  125. delete[] base;
  126. }
  127. break;
  128. }
  129. }
  130. size_t GetLogFileSize() const override {
  131. MutexLock l(&mutex_);
  132. return file_.GetFileSize();
  133. }
  134. private:
  135. WritableFileWriter file_;
  136. mutable port::Mutex mutex_; // Mutex to protect the shared variables below.
  137. const static uint64_t flush_every_seconds_ = 5;
  138. std::atomic_uint_fast64_t last_flush_micros_;
  139. Env* env_;
  140. std::atomic<bool> flush_pending_;
  141. };
  142. } // namespace ROCKSDB_NAMESPACE