aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar Benjamin Barenblat <bbaren@google.com>2021-07-06 19:57:09 -0400
committerGravatar Benjamin Barenblat <bbaren@google.com>2021-07-06 19:57:09 -0400
commitfe480f5e29f212efd5b933475cc6e71fc5937f4d (patch)
treefc274e0a34ea889f6933618393533fdcfa188a65
parentbbec3b57e296543c5005b93ad1d74c6e3ad34a40 (diff)
Add CHECK macro to logging framework
Reviewed-by: Alex Chernyakhovsky <achernya@google.com>
-rw-r--r--buildconf/common.ninja3
-rw-r--r--log.cc17
-rw-r--r--log.h8
-rw-r--r--log_test.cc12
4 files changed, 39 insertions, 1 deletions
diff --git a/buildconf/common.ninja b/buildconf/common.ninja
index 6ec7e96..e3d2298 100644
--- a/buildconf/common.ninja
+++ b/buildconf/common.ninja
@@ -30,8 +30,9 @@ rule link
build gsrsup.o: cxx gsrsup.cc
build gsrsup: link gsrsup.o
+build log.o: cxx log.cc
build log_test.o: cxx log_test.cc
-build log_test: link log_test.o
+build log_test: link log.o log_test.o
libs = -lgmock_main -lgmock -lgtest -labsl_strings -pthread
default gsrsup
diff --git a/log.cc b/log.cc
new file mode 100644
index 0000000..13b74d7
--- /dev/null
+++ b/log.cc
@@ -0,0 +1,17 @@
+#include "log.h"
+
+#include <absl/strings/substitute.h>
+#include <stdlib.h>
+
+namespace gsrsup {
+
+void Check(Log& log, bool condition, const char* condition_str,
+ const char* file, int line) {
+ if (!condition) {
+ log.Error(absl::Substitute("internal error ($0:$1): ", file, line),
+ condition_str);
+ exit(1);
+ }
+}
+
+} // namespace gsrsup
diff --git a/log.h b/log.h
index e0d3963..d588b8f 100644
--- a/log.h
+++ b/log.h
@@ -111,6 +111,14 @@ void Log::Message(Level level, Args... args) {
out_->write(message.data(), message.size());
}
+// If condition is false, logs an internal error and exits the program.
+void Check(Log& log, bool condition, const char* condition_str,
+ const char* file, int line);
+
} // namespace gsrsup
+// A convenience macro to invoke the Check function.
+#define CHECK(log, condition) \
+ ::gsrsup::Check((log), (condition), #condition, __FILE__, __LINE__)
+
#endif // GSRSUP_LOG_H_
diff --git a/log_test.cc b/log_test.cc
index 0ceb3f2..c06fd90 100644
--- a/log_test.cc
+++ b/log_test.cc
@@ -80,5 +80,17 @@ TEST(LogTest, DedicatedErrorFunction) {
EXPECT_THAT(s.str(), HasSubstr("error:"));
}
+TEST(LogTest, CheckPasses) {
+ std::ostringstream s;
+ Log log("program", s);
+ CHECK(log, 2 + 2 == 4);
+ EXPECT_THAT(s.str(), IsEmpty());
+}
+
+TEST(LogDeathTest, CheckFails) {
+ Log log("program", std::cerr);
+ EXPECT_DEATH(CHECK(log, 2 + 2 == 5), "internal error \\(.*\\): 2 \\+ 2 == 5");
+}
+
} // namespace
} // namespace gsrsup