use __android_log_write or __android_log_buf_write based on template paramter

This commit is contained in:
Timo Lange 2022-05-06 08:55:41 +02:00
parent 173d06578f
commit 0a875d7b2d
1 changed files with 28 additions and 5 deletions

View File

@ -16,6 +16,7 @@
# include <mutex>
# include <string>
# include <thread>
# include <type_traits>
# if !defined(SPDLOG_ANDROID_RETRIES)
# define SPDLOG_ANDROID_RETRIES 2
@ -25,9 +26,10 @@ namespace spdlog {
namespace sinks {
/*
* Android sink (logging using __android_log_write)
* Android sink
* (logging using __android_log_write or __android_log_buf_write depending on the specified BufferID)
*/
template<typename Mutex>
template<typename Mutex, int BufferID = log_id::LOG_ID_MAIN>
class android_sink final : public base_sink<Mutex>
{
public:
@ -53,24 +55,39 @@ protected:
const char *msg_output = formatted.data();
// See system/core/liblog/logger_write.c for explanation of return value
int ret = __android_log_write(priority, tag_.c_str(), msg_output);
int ret = android_log(priority, tag_.c_str(), msg_output);
int retry_count = 0;
while ((ret == -11 /*EAGAIN*/) && (retry_count < SPDLOG_ANDROID_RETRIES))
{
details::os::sleep_for_millis(5);
ret = __android_log_write(priority, tag_.c_str(), msg_output);
ret = android_log(priority, tag_.c_str(), msg_output);
retry_count++;
}
if (ret < 0)
{
throw_spdlog_ex("__android_log_write() failed", ret);
throw_spdlog_ex("logging to Android failed", ret);
}
}
void flush_() override {}
private:
// There might be liblog versions used, that do not support __android_log_buf_write. So we only compile and link against
// __android_log_buf_write, if user explicitely provides a non-default log buffer. Otherwise, when using the default log buffer, always
// log via __android_log_write.
template<int ID = BufferID, typename... Args>
typename std::enable_if<ID == static_cast<int>(log_id::LOG_ID_MAIN), int>::type android_log(Args... args)
{
return __android_log_write(std::forward<Args>(args)...);
}
template<int ID = BufferID, typename... Args>
typename std::enable_if<ID != static_cast<int>(log_id::LOG_ID_MAIN), int>::type android_log(Args... args)
{
return __android_log_buf_write(ID, std::forward<Args>(args)...);
}
static android_LogPriority convert_to_android_(spdlog::level::level_enum level)
{
switch (level)
@ -98,6 +115,12 @@ private:
using android_sink_mt = android_sink<std::mutex>;
using android_sink_st = android_sink<details::null_mutex>;
template<int BufferId = log_id::LOG_ID_MAIN>
using android_sink_buf_mt = android_sink<std::mutex, BufferId>;
template<int BufferId = log_id::LOG_ID_MAIN>
using android_sink_buf_st = android_sink<details::null_mutex, BufferId>;
} // namespace sinks
// Create and register android syslog logger