Explorar el Código

Add testing for thread name using a thread_local storage duration global.

Sam Jaffe hace 5 años
padre
commit
ea4052bdac
Se han modificado 3 ficheros con 34 adiciones y 1 borrados
  1. 1 0
      include/logger/detail/data_accessors.h
  2. 6 1
      src/data_accessors.cxx
  3. 27 0
      test/pattern_layout_test.cxx

+ 1 - 0
include/logger/detail/data_accessors.h

@@ -10,6 +10,7 @@ namespace logging {
 namespace logging { namespace detail {
   class thread_info_helper {
   public:
+    static void set_name(std::string const & name);
     std::string thread_id() const;
     std::string thread_name() const;
   };

+ 6 - 1
src/data_accessors.cxx

@@ -38,6 +38,11 @@ namespace {
 }
 
 namespace logging { namespace detail {
+  static thread_local std::string THREAD_NAME;
+  
+  void thread_info_helper::set_name(std::string const & name) {
+    THREAD_NAME = name;
+  }
   
   std::string thread_info_helper::thread_id() const {
     std::stringstream ss;
@@ -46,7 +51,7 @@ namespace logging { namespace detail {
   }
   
   std::string thread_info_helper::thread_name() const {
-    return thread_id();
+    return THREAD_NAME.size() ? THREAD_NAME : thread_id();
   }
   
   std::vector<std::string>

+ 27 - 0
test/pattern_layout_test.cxx

@@ -5,10 +5,13 @@
 //  Created by Sam Jaffe on 4/13/19.
 //
 
+#include <thread>
+
 #include <gmock/gmock.h>
 
 #include "resource_factory/prototype_factory.hpp"
 
+#include "logger/detail/data_accessors.h"
 #include "logger/detail/layout.h"
 #include "logger/exception.h"
 #include "logger/log_manager.h"
@@ -257,6 +260,30 @@ TEST(PatternLayoutTest, CanOutputLocation) {
   EXPECT_THAT(message, testing::MatchesRegex(regex));
 }
 
+TEST(PatternLayoutTest, CanOutputThreadInfoAsThreadId) {
+  using testing::Eq;
+  std::stringstream ss;
+  ss << std::this_thread::get_id();
+  EXPECT_THAT(DoFormat("%t", getpkt("")), Eq(ss.str()));
+}
+
+TEST(PatternLayoutTest, OutputsThreadNameIfAvailable) {
+  using testing::Eq;
+  ::logging::detail::thread_info_helper::set_name("main");
+  EXPECT_THAT(DoFormat("%t", getpkt("")), Eq("main"));
+  ::logging::detail::thread_info_helper::set_name("");
+}
+
+TEST(PatternLayoutTest, ThreadNameIsThreadLocalStorage) {
+  using testing::Ne;
+  ::logging::detail::thread_info_helper::set_name("main");
+  std::thread tr([](){
+    EXPECT_THAT(DoFormat("%t", getpkt("")), Ne("main"));
+  });
+  tr.join();
+  ::logging::detail::thread_info_helper::set_name("");
+}
+
 TEST(PatternLayoutTest, ThrowsOnUnknownToken) {
   using testing::Eq;
   EXPECT_THROW(GetPatternLayout("%q"),