ソースを参照

Add test for "time since creation"

Sam Jaffe 5 年 前
コミット
3e2dcab644
2 ファイル変更26 行追加0 行削除
  1. 13 0
      src/loggers/pattern_layout_format.cxx
  2. 13 0
      test/pattern_layout_test.cxx

+ 13 - 0
src/loggers/pattern_layout_format.cxx

@@ -31,6 +31,17 @@ namespace logging { namespace {
     }
   };
 
+  struct time_elapsed_gen : public format::generator_t {
+    long long created;
+    time_elapsed_gen() : created(millis(now())) {}
+    static long long millis(timeval tv) {
+      return tv.tv_sec * 1000 + tv.tv_usec / 1000;
+    }
+    std::string str(logpacket const & lp) const override {
+      return std::to_string(millis(lp.time) - created);
+    }
+  };
+
   struct level_gen : public format::generator_t {
     std::string str(logpacket const & lp) const override {
       return to_string(lp.level, true);
@@ -235,6 +246,8 @@ namespace logging {
         if (is('{')) next = std::strchr(next, '}');
       } else if (is('F') || is('M') || is('L') || is('l')) {
         out.gen.push_back(std::make_shared<location_info_gen>(*next));
+      } else if (is('r')) {
+        out.gen.push_back(std::make_shared<time_elapsed_gen>());
       } else {
         out.gen.push_back(handle(next));
       }

+ 13 - 0
test/pattern_layout_test.cxx

@@ -153,6 +153,19 @@ TEST(PatternLayoutTest, LogMessageIsMToken) {
               Eq("HELLO"));
 }
 
+MATCHER_P2(Near, value, error, "") {
+  return std::abs(arg - value) < error;
+}
+
+TEST(PatternLayoutTest, CanOutputTimeSinceCreation) {
+  // Because we're passing in a timestamp of {0, 0} with getpkt(), %r should
+  // produce -1 * time_since_epoch_in_milliseconds().
+  // Since time(NULL) returns seconds, whereas %r returns milliseconds, we
+  // allow a margin of error of +/- 1 second
+  EXPECT_THAT(std::stoll(DoFormat("%r", getpkt(""))),
+              Near(-time(NULL) * 1000, 1000));
+}
+
 TEST(PatternLayoutTest, CanOutputLineNumber) {
   EXPECT_THAT(std::stoi(DoFormat("%L", getpkt("", log_here))),
              testing::Eq(__LINE__ - 1));