1 #ifndef GENESIS_UTILS_CORE_RESOURCE_LOGGER_H_
2 #define GENESIS_UTILS_CORE_RESOURCE_LOGGER_H_
44 #include <condition_variable>
65 using OutputSink = std::function<void(
const std::string&)>;
76 ResourceLogger( std::chrono::duration<int> interval, std::string
const& log_file )
106 logging_thread_ = std::thread( &ResourceLogger::logging_worker_thread_,
this );
112 std::lock_guard<std::mutex> lock(logging_mutex_);
118 logging_cv_.notify_all();
119 if( logging_thread_.joinable() ) {
120 logging_thread_.join();
127 std::lock_guard<std::mutex> lock(logging_mutex_);
128 interval_ = new_interval;
130 logging_cv_.notify_all();
137 sink( make_header_() );
139 std::unique_lock<std::mutex> lock( sink_mutex_ );
140 output_sinks_.push_back(sink);
143 void log_to_file( std::string
const& log_file,
bool write_header =
true )
145 auto target = std::make_shared<std::ofstream>();
148 [target]( std::string
const& message ){
149 (*target) << message << std::endl;
158 []( std::string
const& message ) {
159 std::cout << message << std::endl;
168 []( std::string
const& message ) {
169 std::cerr << message << std::endl;
181 std::string make_header_()
183 return "date\ttime\tfiles\tmem\tcpu\ttasks";
186 std::string make_log_message_()
190 std::stringstream ss;
204 void log_message_to_sinks_()
206 auto const message = make_log_message_();
207 std::unique_lock<std::mutex> lock( sink_mutex_ );
208 for(
auto& sink : output_sinks_ ) {
213 void logging_worker_thread_()
217 log_message_to_sinks_();
224 std::unique_lock<std::mutex> lock(logging_mutex_);
225 if( logging_cv_.wait_for( lock, interval_, [
this] { return !running_; })) {
230 log_message_to_sinks_();
238 std::chrono::duration<int> interval_;
239 std::atomic<bool> running_;
241 std::thread logging_thread_;
242 std::mutex logging_mutex_;
243 std::condition_variable logging_cv_;
245 std::mutex sink_mutex_;
246 std::vector<OutputSink> output_sinks_;
253 #endif // include guard