Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

android: Support __android_log_write_log_message based logging #3155

Open
wants to merge 1 commit into
base: v1.x
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion include/spdlog/sinks/android_sink.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
#define SPDLOG_ANDROID_RETRIES 2
#endif

#if __ANDROID_API__ >= 30
#define SPDLOG_ANDROID_ENABLE_LOG_WRITE
#endif

namespace spdlog {
namespace sinks {

Expand All @@ -35,7 +39,12 @@ class android_sink final : public base_sink<Mutex> {
public:
explicit android_sink(std::string tag = "spdlog", bool use_raw_msg = false)
: tag_(std::move(tag)),
use_raw_msg_(use_raw_msg) {}
use_raw_msg_(use_raw_msg) {
// Available since API level 30
#ifdef SPDLOG_ANDROID_ENABLE_LOG_WRITE
write_message_ = (write_log_message_t)dlsym(nullptr, "__android_log_write_log_message");
#endif
}

protected:
void sink_it_(const details::log_msg &msg) override {
Expand All @@ -49,6 +58,21 @@ class android_sink final : public base_sink<Mutex> {
formatted.push_back('\0');
const char *msg_output = formatted.data();

#ifdef SPDLOG_ANDROID_ENABLE_LOG_WRITE
if (write_message_) {
__android_log_message logMessage{};
logMessage.struct_size = sizeof(logMessage);
logMessage.buffer_id = BufferID;
logMessage.priority = priority;
logMessage.tag = tag_.c_str();
logMessage.file = msg.source.filename;
logMessage.line = static_cast<uint32_t>(msg.source.line);
logMessage.message = msg_output;
write_message_(&logMessage);
return;
}
#endif

// See system/core/liblog/logger_write.c for explanation of return value
int ret = android_log(priority, tag_.c_str(), msg_output);
if (ret == -EPERM) {
Expand Down Expand Up @@ -104,8 +128,15 @@ class android_sink final : public base_sink<Mutex> {
}
}

#ifdef SPDLOG_ANDROID_ENABLE_LOG_WRITE
typedef void (*write_log_message_t)(struct __android_log_message *log_message);
#endif

std::string tag_;
bool use_raw_msg_;
#ifdef SPDLOG_ANDROID_ENABLE_LOG_WRITE
write_log_message_t write_message_;
#endif
};

using android_sink_mt = android_sink<std::mutex>;
Expand Down