otsdaq-mu2e-stm  5.02.01
async_logger.hh
1 #ifndef ASYNC_LOGGER_hh_
2 #define ASYNC_LOGGER_hh_
3 
4 #include <iostream>
5 #include <string>
6 #include <queue>
7 #include <thread>
8 #include <mutex>
9 #include <condition_variable>
10 #include <atomic>
11 #include <utility> // For std::pair
12 
13 // Include CPU utils header
14 #include "Mu2e-STMDAQ/utils/cpu_utils.hh"
15 // Logger code
16 #include "Mu2e-STMDAQ/utils/Logger.hh"
17 // Environmental variables header
18 #include "Mu2e-STMDAQ/utils/EnvVars.hh"
19 // Timer code
20 #include "Mu2e-STMDAQ/utils/timer.hh"
21 
22 // Pre-allocated buffer pool for memory reuse
23 class AsyncLogger {
24 
25 public:
26 
27  using Message = std::pair<std::string, unsigned int>; // Alias for readability
28 
29  // Constructor
30  AsyncLogger(const Config& cfg, const std::shared_ptr<cpu_utils>& cpu_);
31 
32  // Destructor for logging
33  ~AsyncLogger(){
34  {
35  std::lock_guard<std::mutex> lock(queueMutex);
36  done = true;
37  }
38  cv.notify_all(); // Notify the thread to stop waiting
39  if (printerThread.joinable()) {
40  printerThread.join(); // Ensure the thread is joined cleanly
41  }
42 
43  // Close log file
44  LoggerSTM::Instance()->CloseLogFile();
45 
46  std::cout << "AsyncLogger destructor called.\n";
47  }
48 
49  // Function to log a message
50  void log(const std::string& msg, unsigned int level);
51 
52 private:
53 
54  std::queue<Message> messageQueue; // Thread-safe message queue
55  std::mutex queueMutex; // Mutex to protect the queue
56  std::condition_variable cv; // Condition variable for notifications
57  std::atomic<bool> done; // Flag to signal shutdown
58  std::thread printerThread; // The dedicated printer thread
59 
60  // The printer thread function
61  void printerThreadFunc();
62 
63  // Store reference to the Config instance
64  const Config& cfg;
65 
66  // Store reference to CPU utils instance
67  const std::shared_ptr<cpu_utils>& cpu;
68 
69 };
70 
71 #endif
Definition: config.hh:19