NDK输出cout日志

StreamBuf.cpp 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <streambuf>
#include <string>
#include <android/log.h>

class StreamBuf : public std::streambuf
{
enum
{
BUFFER_SIZE = 255,
};

public:
StreamBuf()
{
buffer_[BUFFER_SIZE] = '\0';
setp(buffer_, buffer_ + BUFFER_SIZE - 1);
}

~StreamBuf()
{
sync();
}

protected:
virtual int_type overflow(int_type c)
{
if (c != EOF)
{
*pptr() = c;
pbump(1);
}
flush_buffer();
return c;
}

virtual int sync()
{
flush_buffer();
return 0;
}

private:
int flush_buffer()
{
int len = int(pptr() - pbase());
if (len <= 0)
return 0;

if (len <= BUFFER_SIZE)
buffer_[len] = '\0';

#ifdef ANDROID
android_LogPriority t = ANDROID_LOG_INFO;
__android_log_write(t, "mylog", buffer_);
#else
printf("%s", buffer_);
#endif

pbump(-len);
return len;
}

private:
char buffer_[BUFFER_SIZE + 1];
};

如何调用

1
2
3
4
5
6
StreamBuf g_StreamBuf;
std::cout.rdbuf(&g_StreamBuf);

//NOTE: std::endl会立即调用sync方法将缓冲区字符写入log,并不只是换行用
std::cout << "hello " << 123 << std::endl;
std::cout << "pi = " << 3.14 << std::endl;

坚持原创技术分享,您的支持将鼓励我继续创作!