win_logger.cc 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 can be shared by all environments
  11. // where enough posix functionality is available.
  12. #if defined(OS_WIN)
  13. #include "port/win/win_logger.h"
  14. #include <fcntl.h>
  15. #include <stdio.h>
  16. #include <time.h>
  17. #include <algorithm>
  18. #include <atomic>
  19. #include "monitoring/iostats_context_imp.h"
  20. #include "port/sys_time.h"
  21. #include "port/win/env_win.h"
  22. #include "port/win/io_win.h"
  23. #include "rocksdb/env.h"
  24. #include "rocksdb/system_clock.h"
  25. namespace ROCKSDB_NAMESPACE {
  26. namespace port {
  27. WinLogger::WinLogger(uint64_t (*gettid)(), SystemClock* clock, HANDLE file,
  28. const InfoLogLevel log_level)
  29. : Logger(log_level),
  30. file_(file),
  31. gettid_(gettid),
  32. log_size_(0),
  33. last_flush_micros_(0),
  34. clock_(clock),
  35. flush_pending_(false) {
  36. assert(file_ != NULL);
  37. assert(file_ != INVALID_HANDLE_VALUE);
  38. }
  39. void WinLogger::DebugWriter(const char* str, int len) {
  40. assert(file_ != INVALID_HANDLE_VALUE);
  41. DWORD bytesWritten = 0;
  42. BOOL ret = WriteFile(file_, str, len, &bytesWritten, NULL);
  43. if (ret == FALSE) {
  44. std::string errSz = GetWindowsErrSz(GetLastError());
  45. fprintf(stderr, "%s", errSz.c_str());
  46. }
  47. }
  48. WinLogger::~WinLogger() { CloseInternal().PermitUncheckedError(); }
  49. Status WinLogger::CloseImpl() { return CloseInternal(); }
  50. Status WinLogger::CloseInternal() {
  51. Status s;
  52. if (INVALID_HANDLE_VALUE != file_) {
  53. BOOL ret = FlushFileBuffers(file_);
  54. if (ret == 0) {
  55. auto lastError = GetLastError();
  56. s = IOErrorFromWindowsError("Failed to flush LOG on Close() ", lastError);
  57. }
  58. ret = CloseHandle(file_);
  59. // On error the return value is zero
  60. if (ret == 0 && s.ok()) {
  61. auto lastError = GetLastError();
  62. s = IOErrorFromWindowsError("Failed to flush LOG on Close() ", lastError);
  63. }
  64. file_ = INVALID_HANDLE_VALUE;
  65. closed_ = true;
  66. }
  67. return s;
  68. }
  69. void WinLogger::Flush() {
  70. assert(file_ != INVALID_HANDLE_VALUE);
  71. if (flush_pending_) {
  72. flush_pending_ = false;
  73. // With Windows API writes go to OS buffers directly so no fflush needed
  74. // unlike with C runtime API. We don't flush all the way to disk
  75. // for perf reasons.
  76. }
  77. last_flush_micros_ = clock_->NowMicros();
  78. }
  79. void WinLogger::Logv(const char* format, va_list ap) {
  80. IOSTATS_TIMER_GUARD(logger_nanos);
  81. assert(file_ != INVALID_HANDLE_VALUE);
  82. const uint64_t thread_id = (*gettid_)();
  83. // We try twice: the first time with a fixed-size stack allocated buffer,
  84. // and the second time with a much larger dynamically allocated buffer.
  85. char buffer[500];
  86. std::unique_ptr<char[]> largeBuffer;
  87. for (int iter = 0; iter < 2; ++iter) {
  88. char* base;
  89. int bufsize;
  90. if (iter == 0) {
  91. bufsize = sizeof(buffer);
  92. base = buffer;
  93. } else {
  94. bufsize = 30000;
  95. largeBuffer.reset(new char[bufsize]);
  96. base = largeBuffer.get();
  97. }
  98. char* p = base;
  99. char* limit = base + bufsize;
  100. port::TimeVal now_tv;
  101. port::GetTimeOfDay(&now_tv, nullptr);
  102. const time_t seconds = now_tv.tv_sec;
  103. struct tm t;
  104. localtime_s(&t, &seconds);
  105. p += snprintf(p, limit - p, "%04d/%02d/%02d-%02d:%02d:%02d.%06d %llx ",
  106. t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour,
  107. t.tm_min, t.tm_sec, static_cast<int>(now_tv.tv_usec),
  108. static_cast<long long unsigned int>(thread_id));
  109. // Print the message
  110. if (p < limit) {
  111. va_list backup_ap;
  112. va_copy(backup_ap, ap);
  113. int done = vsnprintf(p, limit - p, format, backup_ap);
  114. if (done > 0) {
  115. p += done;
  116. } else {
  117. continue;
  118. }
  119. va_end(backup_ap);
  120. }
  121. // Truncate to available space if necessary
  122. if (p >= limit) {
  123. if (iter == 0) {
  124. continue; // Try again with larger buffer
  125. } else {
  126. p = limit - 1;
  127. }
  128. }
  129. // Add newline if necessary
  130. if (p == base || p[-1] != '\n') {
  131. *p++ = '\n';
  132. }
  133. assert(p <= limit);
  134. const size_t write_size = p - base;
  135. DWORD bytesWritten = 0;
  136. BOOL ret = WriteFile(file_, base, static_cast<DWORD>(write_size),
  137. &bytesWritten, NULL);
  138. if (ret == FALSE) {
  139. std::string errSz = GetWindowsErrSz(GetLastError());
  140. fprintf(stderr, "%s", errSz.c_str());
  141. }
  142. flush_pending_ = true;
  143. assert((bytesWritten == write_size) || (ret == FALSE));
  144. if (bytesWritten > 0) {
  145. log_size_ += write_size;
  146. }
  147. uint64_t now_micros =
  148. static_cast<uint64_t>(now_tv.tv_sec) * 1000000 + now_tv.tv_usec;
  149. if (now_micros - last_flush_micros_ >= flush_every_seconds_ * 1000000) {
  150. flush_pending_ = false;
  151. // With Windows API writes go to OS buffers directly so no fflush needed
  152. // unlike with C runtime API. We don't flush all the way to disk
  153. // for perf reasons.
  154. last_flush_micros_ = now_micros;
  155. }
  156. break;
  157. }
  158. }
  159. size_t WinLogger::GetLogFileSize() const { return log_size_; }
  160. } // namespace port
  161. } // namespace ROCKSDB_NAMESPACE
  162. #endif