stderr_logger.cc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (c) Meta Platforms, Inc. and affiliates.
  2. //
  3. // This source code is licensed under both the GPLv2 (found in the
  4. // COPYING file in the root directory) and Apache 2.0 License
  5. // (found in the LICENSE.Apache file in the root directory).
  6. #include "util/stderr_logger.h"
  7. #include "port/malloc.h"
  8. #include "port/sys_time.h"
  9. namespace ROCKSDB_NAMESPACE {
  10. StderrLogger::~StderrLogger() {
  11. if (log_prefix != nullptr) {
  12. free((void*)log_prefix);
  13. }
  14. }
  15. void StderrLogger::Logv(const char* format, va_list ap) {
  16. const uint64_t thread_id = Env::Default()->GetThreadID();
  17. port::TimeVal now_tv;
  18. port::GetTimeOfDay(&now_tv, nullptr);
  19. const time_t seconds = now_tv.tv_sec;
  20. struct tm t;
  21. port::LocalTimeR(&seconds, &t);
  22. // The string we eventually log has three parts: the context (time, thread),
  23. // optional user-supplied prefix, and the actual log message (the "suffix").
  24. //
  25. // We compute their lengths so that we can allocate a buffer big enough to
  26. // print it. The context string (with the date and thread id) is really only
  27. // 44 bytes, but we allocate 50 to be safe.
  28. //
  29. // ctx_len = 44 = ( 4+ 1+ 2+1+2+ 1+2+ 1+2+ 1+ 2+1+6+ 1+16+1)
  30. const char* ctx_prefix_fmt = "%04d/%02d/%02d-%02d:%02d:%02d.%06d %llx %s";
  31. size_t ctx_len = 50;
  32. va_list ap_copy;
  33. va_copy(ap_copy, ap);
  34. const size_t log_suffix_len = vsnprintf(nullptr, 0, format, ap_copy) + 1;
  35. va_end(ap_copy);
  36. // Allocate space for the context, log_prefix, and log itself
  37. // Extra byte for null termination
  38. size_t buf_len = ctx_len + log_prefix_len + log_suffix_len;
  39. std::unique_ptr<char[]> buf(new char[buf_len]);
  40. // If the logger was created without a prefix, the prefix is a nullptr
  41. const char* prefix = log_prefix == nullptr ? "" : log_prefix;
  42. // Write out the context and prefix string
  43. int written =
  44. snprintf(buf.get(), ctx_len + log_prefix_len, ctx_prefix_fmt,
  45. t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min,
  46. t.tm_sec, static_cast<int>(now_tv.tv_usec),
  47. static_cast<long long unsigned int>(thread_id), prefix);
  48. vsnprintf(buf.get() + written, log_suffix_len, format, ap);
  49. fprintf(stderr, "%s%c", buf.get(), '\n');
  50. }
  51. } // namespace ROCKSDB_NAMESPACE