Blame view

include/threadcontext.h 2.05 KB
25b0d2f8   Peter M. Groen   Setting up Loggin...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  #pragma once
  
  // std
  #include <string>
  
  namespace osdev {
  namespace components {
  namespace mqtt {
  
  /**
   * @brief   Set the current thread context
   * The context is restored to the previous context when this object goes out of scope.
   * @note This object is meat to be used on the stack.
   */
  class ThreadContextScope
  {
  public:
      /**
       * @brief   Construct a scoped object that sets the current thread context.
       * @param   context The context that will be used by the loggin framework.
       */
      explicit ThreadContextScope( const std::string &context );
      ~ThreadContextScope();
  
      // Non copyable and non movable
      ThreadContextScope( const ThreadContextScope& ) = delete;
      ThreadContextScope& operator=( const ThreadContextScope& ) = delete;
      ThreadContextScope( ThreadContextScope&& ) = delete;
      ThreadContextScope& operator=( ThreadContextScope&& ) = delete;
  
  private:
      std::string m_previousContext;  ///< Copy of the previous context.
  };
  
  /**
   * @brief   Add context to a thread.
   * For every thread only one specific instance of this object will exist.
   * @note Contexts can only be set by using a ThreadContextScope object.
   */
  class ThreadContext
  {
      // Contexts can only be set by using the ThreadContextScope object.
      friend class ThreadContextScope;
  
  public:
      static ThreadContext& instance();
  
84738f56   Peter M. Groen   Setting up the lo...
48
49
50
51
52
53
      const std::string& context() const
      {
          return m_context;
      }
  
  private:
25b0d2f8   Peter M. Groen   Setting up Loggin...
54
      /**
84738f56   Peter M. Groen   Setting up the lo...
55
       * @brief Set the thread context.
25b0d2f8   Peter M. Groen   Setting up Loggin...
56
       */
84738f56   Peter M. Groen   Setting up the lo...
57
      void setContext( const std::string &contextString )
25b0d2f8   Peter M. Groen   Setting up Loggin...
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
      {
          m_context = contextString;
      }
  
      /**
       * Construct a ThreadContext object.
       * The context is set to "default"
       */
      ThreadContext();
  
      // Non copyable and non moveable
      ThreadContext(const ThreadContext&) = delete;
      ThreadContext& operator=(const ThreadContext&) = delete;
      ThreadContext(ThreadContext&&) = delete;
      ThreadContext& operator=(ThreadContext&&) = delete;
  
      std::string m_context;  ///< The context string
  };
  
  }   // End namespace mqtt
  }   // End namespace components
  }   // End namespace osdev