84c8e0d6882e49ee23cf890784f889690fcd724a
[folly.git] / folly / experimental / logging / LogStreamProcessor.cpp
1 /*
2  * Copyright 2004-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 #include <folly/experimental/logging/LogStreamProcessor.h>
17
18 #include <cassert>
19
20 #include <folly/experimental/logging/LogStream.h>
21
22 namespace folly {
23 void LogStreamProcessor::operator&(std::ostream& stream) noexcept {
24   // Note that processMessage() is not noexcept and theoretically may throw.
25   // However, the only exception that should be possible is std::bad_alloc if
26   // we fail to allocate memory.  We intentionally let our noexcept specifier
27   // crash in that case, since the program likely won't be able to continue
28   // anyway.
29   //
30   // Any other error here is unexpected and we also want to fail hard
31   // in that situation too.
32   auto& logStream = static_cast<LogStream&>(stream);
33   category_->processMessage(LogMessage{category_,
34                                        level_,
35                                        filename_,
36                                        lineNumber_,
37                                        extractMessageString(logStream)});
38 }
39
40 void LogStreamProcessor::operator&(LogStream&& stream) noexcept {
41   // This version of operator&() is generally only invoked when
42   // no streaming arguments were supplied to the logging macro.
43   // Therefore we don't bother calling extractMessageString(stream),
44   // and just directly use message_.
45   DCHECK(stream.empty());
46
47   category_->processMessage(LogMessage{
48       category_, level_, filename_, lineNumber_, std::move(message_)});
49 }
50
51 std::string LogStreamProcessor::extractMessageString(
52     LogStream& stream) noexcept {
53   if (stream.empty()) {
54     return std::move(message_);
55   }
56
57   if (message_.empty()) {
58     return stream.extractString();
59   }
60   message_.append(stream.extractString());
61   return std::move(message_);
62 }
63 }