1 // 2 // Copyright(c) 2015 Gabi Melman. 3 // Distributed under the MIT License (http://opensource.org/licenses/MIT) 4 // 5 6 #pragma once 7 8 #if defined(__ANDROID__) 9 10 #include <spdlog/sinks/sink.h> 11 12 #include <mutex> 13 #include <string> 14 #include <android/log.h> 15 16 namespace spdlog 17 { 18 namespace sinks 19 { 20 21 /* 22 * Android sink (logging using __android_log_write) 23 * __android_log_write is thread-safe. No lock is needed. 24 */ 25 class android_sink : public sink 26 { 27 public: _tag(tag)28 explicit android_sink(const std::string& tag = "spdlog"): _tag(tag) {} 29 log(const details::log_msg & msg)30 void log(const details::log_msg& msg) override 31 { 32 const android_LogPriority priority = convert_to_android(msg.level); 33 // See system/core/liblog/logger_write.c for explanation of return value 34 const int ret = __android_log_write( 35 priority, _tag.c_str(), msg.formatted.c_str() 36 ); 37 if (ret < 0) 38 { 39 throw spdlog_ex("__android_log_write() failed", ret); 40 } 41 } 42 flush()43 void flush() override 44 { 45 } 46 47 private: convert_to_android(spdlog::level::level_enum level)48 static android_LogPriority convert_to_android(spdlog::level::level_enum level) 49 { 50 switch(level) 51 { 52 case spdlog::level::trace: 53 return ANDROID_LOG_VERBOSE; 54 case spdlog::level::debug: 55 return ANDROID_LOG_DEBUG; 56 case spdlog::level::info: 57 return ANDROID_LOG_INFO; 58 case spdlog::level::warn: 59 return ANDROID_LOG_WARN; 60 case spdlog::level::err: 61 return ANDROID_LOG_ERROR; 62 case spdlog::level::critical: 63 return ANDROID_LOG_FATAL; 64 default: 65 return ANDROID_LOG_DEFAULT; 66 } 67 } 68 69 std::string _tag; 70 }; 71 72 } 73 } 74 75 #endif 76