Blame view

include/threadcontext.h 1.96 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
  #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();
  
      /**
       * @briefReturn the thread context.
       */
      void setContext( const std::string &contextString)
      {
          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