GLog.h 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright 2012-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <atomic>
  18. #include <chrono>
  19. #include <glog/logging.h>
  20. #ifndef FB_LOG_EVERY_MS
  21. /**
  22. * Issues a LOG(severity) no more often than every
  23. * milliseconds. Example:
  24. *
  25. * FB_LOG_EVERY_MS(INFO, 10000) << "At least ten seconds passed"
  26. * " since you last saw this.";
  27. *
  28. * The implementation uses for statements to introduce variables in
  29. * a nice way that doesn't mess surrounding statements. It is thread
  30. * safe. Non-positive intervals will always log.
  31. */
  32. #define FB_LOG_EVERY_MS(severity, milli_interval) \
  33. for (decltype(milli_interval) FB_LEM_once = 1, \
  34. FB_LEM_interval = (milli_interval); \
  35. FB_LEM_once;) \
  36. for (::std::chrono::milliseconds::rep FB_LEM_prev, \
  37. FB_LEM_now = FB_LEM_interval <= 0 \
  38. ? 0 \
  39. : ::std::chrono::duration_cast<::std::chrono::milliseconds>( \
  40. ::std::chrono::system_clock::now().time_since_epoch()) \
  41. .count(); \
  42. FB_LEM_once;) \
  43. for (static ::std::atomic<::std::chrono::milliseconds::rep> FB_LEM_hist; \
  44. FB_LEM_once; \
  45. FB_LEM_once = 0) \
  46. if (FB_LEM_interval > 0 && \
  47. (FB_LEM_now - \
  48. (FB_LEM_prev = \
  49. FB_LEM_hist.load(std::memory_order_acquire)) < \
  50. FB_LEM_interval || \
  51. !FB_LEM_hist.compare_exchange_strong(FB_LEM_prev, FB_LEM_now))) { \
  52. } else \
  53. LOG(severity)
  54. #endif