2
0

Logging.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (c) 2016-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. */
  9. #pragma once
  10. #include <cstdio>
  11. #include <mutex>
  12. namespace pzstd {
  13. constexpr int kLogError = 1;
  14. constexpr int kLogInfo = 2;
  15. constexpr int kLogDebug = 3;
  16. constexpr int kLogVerbose = 4;
  17. class Logger {
  18. std::mutex mutex_;
  19. FILE* out_;
  20. const int level_;
  21. using Clock = std::chrono::system_clock;
  22. Clock::time_point lastUpdate_;
  23. std::chrono::milliseconds refreshRate_;
  24. public:
  25. explicit Logger(int level, FILE* out = stderr)
  26. : out_(out), level_(level), lastUpdate_(Clock::now()),
  27. refreshRate_(150) {}
  28. bool logsAt(int level) {
  29. return level <= level_;
  30. }
  31. template <typename... Args>
  32. void operator()(int level, const char *fmt, Args... args) {
  33. if (level > level_) {
  34. return;
  35. }
  36. std::lock_guard<std::mutex> lock(mutex_);
  37. std::fprintf(out_, fmt, args...);
  38. }
  39. template <typename... Args>
  40. void update(int level, const char *fmt, Args... args) {
  41. if (level > level_) {
  42. return;
  43. }
  44. std::lock_guard<std::mutex> lock(mutex_);
  45. auto now = Clock::now();
  46. if (now - lastUpdate_ > refreshRate_) {
  47. lastUpdate_ = now;
  48. std::fprintf(out_, "\r");
  49. std::fprintf(out_, fmt, args...);
  50. }
  51. }
  52. void clear(int level) {
  53. if (level > level_) {
  54. return;
  55. }
  56. std::lock_guard<std::mutex> lock(mutex_);
  57. std::fprintf(out_, "\r%79s\r", "");
  58. }
  59. };
  60. }