LogStream.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright 2017-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 <ostream>
  18. #include <folly/logging/LogCategory.h>
  19. #include <folly/logging/LogMessage.h>
  20. namespace folly {
  21. /**
  22. * A std::streambuf implementation for use by LogStream
  23. */
  24. class LogStreamBuffer : public std::streambuf {
  25. public:
  26. LogStreamBuffer() {
  27. // We intentionally do not reserve any string buffer space initially,
  28. // since this will not be needed for XLOG() and XLOGF() statements
  29. // that do not use the streaming API. (e.g., XLOG(INFO, "test ", 1234) )
  30. }
  31. bool empty() const {
  32. return str_.empty();
  33. }
  34. std::string extractString() {
  35. str_.resize(pptr() - (&str_.front()));
  36. return std::move(str_);
  37. }
  38. int_type overflow(int_type ch) override;
  39. private:
  40. enum : size_t { kInitialCapacity = 256 };
  41. std::string str_;
  42. };
  43. class LogStreamProcessor;
  44. /**
  45. * A std::ostream implementation for use by the logging macros.
  46. *
  47. * All-in-all this is pretty similar to std::stringstream, but lets us
  48. * destructively extract an rvalue-reference to the underlying string.
  49. */
  50. class LogStream : public std::ostream {
  51. public:
  52. // Explicitly declare the default constructor and destructor, but only
  53. // define them in the .cpp file. This prevents them from being inlined at
  54. // each FB_LOG() or XLOG() statement. Inlining them just causes extra code
  55. // bloat, with minimal benefit--for debug log statements these never even get
  56. // called in the common case where the log statement is disabled.
  57. explicit LogStream(LogStreamProcessor* processor);
  58. ~LogStream();
  59. bool empty() const {
  60. return buffer_.empty();
  61. }
  62. std::string extractString() {
  63. return buffer_.extractString();
  64. }
  65. LogStreamProcessor* getProcessor() const {
  66. return processor_;
  67. }
  68. private:
  69. LogStreamBuffer buffer_;
  70. LogStreamProcessor* const processor_;
  71. };
  72. } // namespace folly