bitz-server  2.0.0
android_sink.h
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 "../details/os.h"
11 #include "sink.h"
12 
13 #include <android/log.h>
14 #include <chrono>
15 #include <mutex>
16 #include <string>
17 #include <thread>
18 
19 #if !defined(SPDLOG_ANDROID_RETRIES)
20 #define SPDLOG_ANDROID_RETRIES 2
21 #endif
22 
23 namespace spdlog {
24 namespace sinks {
25 
26 /*
27  * Android sink (logging using __android_log_write)
28  * __android_log_write is thread-safe. No lock is needed.
29  */
30 class android_sink : public sink
31 {
32 public:
33  explicit android_sink(const std::string &tag = "spdlog", bool use_raw_msg = false)
34  : _tag(tag)
35  , _use_raw_msg(use_raw_msg)
36  {
37  }
38 
39  void log(const details::log_msg &msg) override
40  {
41  const android_LogPriority priority = convert_to_android(msg.level);
42  const char *msg_output = (_use_raw_msg ? msg.raw.c_str() : msg.formatted.c_str());
43 
44  // See system/core/liblog/logger_write.c for explanation of return value
45  int ret = __android_log_write(priority, _tag.c_str(), msg_output);
46  int retry_count = 0;
47  while ((ret == -11 /*EAGAIN*/) && (retry_count < SPDLOG_ANDROID_RETRIES))
48  {
49  details::os::sleep_for_millis(5);
50  ret = __android_log_write(priority, _tag.c_str(), msg_output);
51  retry_count++;
52  }
53 
54  if (ret < 0)
55  {
56  throw spdlog_ex("__android_log_write() failed", ret);
57  }
58  }
59 
60  void flush() override {}
61 
62 private:
63  static android_LogPriority convert_to_android(spdlog::level::level_enum level)
64  {
65  switch (level)
66  {
67  case spdlog::level::trace:
68  return ANDROID_LOG_VERBOSE;
69  case spdlog::level::debug:
70  return ANDROID_LOG_DEBUG;
71  case spdlog::level::info:
72  return ANDROID_LOG_INFO;
73  case spdlog::level::warn:
74  return ANDROID_LOG_WARN;
75  case spdlog::level::err:
76  return ANDROID_LOG_ERROR;
77  case spdlog::level::critical:
78  return ANDROID_LOG_FATAL;
79  default:
80  return ANDROID_LOG_DEFAULT;
81  }
82  }
83 
84  std::string _tag;
85  bool _use_raw_msg;
86 };
87 
88 } // namespace sinks
89 } // namespace spdlog
90 
91 #endif
Definition: async_logger.h:26