refactor logger: add a write_wait method to avoid code duplication

This commit is contained in:
Beat Küng 2016-05-04 11:22:05 +02:00 committed by Lorenz Meier
parent 768e5ab66f
commit 63bd2cebf9
3 changed files with 26 additions and 30 deletions

View File

@ -33,6 +33,10 @@ public:
void stop_log();
/**
* Write data to be logged. The caller must call lock() before calling this.
* @return true on success, false if not enough space in the buffer left
*/
bool write(void *ptr, size_t size);
void lock()

View File

@ -701,6 +701,18 @@ void Logger::stop_log()
_writer.stop_log();
}
bool Logger::write_wait(void *ptr, size_t size)
{
while (!_writer.write(ptr, size)) {
_writer.unlock();
_writer.notify();
usleep(_log_interval);
_writer.lock();
}
return true;
}
void Logger::write_formats()
{
_writer.lock();
@ -714,12 +726,7 @@ void Logger::write_formats()
size_t msg_size = sizeof(msg) - sizeof(msg.format) + msg.format_len;
msg.msg_size = msg_size - 3;
while (!_writer.write(&msg, msg_size)) {
_writer.unlock();
_writer.notify();
usleep(_log_interval); // Wait if buffer is full, don't skip FORMAT messages
_writer.lock();
}
write_wait(&msg, msg_size);
msg_id++;
}
@ -748,14 +755,7 @@ void Logger::write_info(const char *name, const char *value)
msg->msg_size = msg_size - 3;
/* write message */
while (!_writer.write(buffer, msg_size)) {
/* wait if buffer is full, don't skip INFO messages */
_writer.unlock();
_writer.notify();
usleep(_log_interval);
_writer.lock();
}
write_wait(buffer, msg_size);
}
}
@ -815,14 +815,7 @@ void Logger::write_parameters()
msg->msg_size = msg_size - 3;
/* write message */
while (!_writer.write(buffer, msg_size)) {
/* wait if buffer is full, don't skip PARAMETER messages */
_writer.unlock();
_writer.notify();
usleep(_log_interval);
_writer.lock();
}
write_wait(buffer, msg_size);
}
} while ((param != PARAM_INVALID) && (param_idx < (int) param_count()));
@ -882,14 +875,7 @@ void Logger::write_changed_parameters()
/* msg_size is now 1 (msg_type) + 2 (msg_size) + 1 (key_len) + key_len + value_size */
msg->msg_size = msg_size - 3;
/* write message */
while (!_writer.write(buffer, msg_size)) {
/* wait if buffer is full, don't skip PARAMETER messages */
_writer.unlock();
_writer.notify();
usleep(_log_interval);
_writer.lock();
}
write_wait(buffer, msg_size);
}
} while ((param != PARAM_INVALID) && (param_idx < (int) param_count()));

View File

@ -80,6 +80,12 @@ private:
bool copy_if_updated_multi(orb_id_t topic, int multi_instance, int *handle, void *buffer, uint64_t *time_last_checked);
/**
* Write data to the logger. Waits if buffer is full until all data is written.
* Must be called with _writer.lock() held.
*/
bool write_wait(void *ptr, size_t size);
static constexpr size_t MAX_TOPICS_NUM = 128; /**< Maximum number of logged topics */
static constexpr unsigned MAX_NO_LOGFOLDER = 999; /**< Maximum number of log dirs */
static constexpr unsigned MAX_NO_LOGFILE = 999; /**< Maximum number of log files */