安卓jni毫秒级打印

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
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <string>
 
using namespace std;
 
void ivrLog(const char *format, ...)
{
	va_list argptr;
	char buf[1024 * 2];
 
	va_start(argptr, format);
	vsprintf(buf, format, argptr);
	va_end(argptr);
 
	struct timeval tv;
	int iRet = gettimeofday(&tv, NULL);
	time_t t = tv.tv_sec;
	tm* local = localtime(&t);
	char timeBuf[256];
	strftime(timeBuf, 254, "[%Y-%m-%d %H:%M:%S", local);
	sprintf(timeBuf + strlen(timeBuf), ":%d] ", (int)(tv.tv_usec / 1000));
	string dispStr = timeBuf;
	dispStr += buf;
 
	printf("%s", dispStr.c_str());
 
	// please ensure /sdcard/Test dir existed first
	char *logFileName = (char *)"/sdcard/Test/log.txt";
 
	int fd = open(logFileName, O_CREAT|O_WRONLY|O_APPEND, 0666);
	if (fd != -1)
	{
		write(fd, dispStr.c_str(), dispStr.length());
		close(fd);
	}
}