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