我试图在Android上运行一些GMock / GTest测试。这些都运行良好,但没有输出,因为GMock记录到stdout。
我试过以下没有运气(可能是因为它是针对Dalvik VM,他们已经在Android 5中取消了它):
$ adb shell stop
$ adb shell setprop log.redirect-stdio true
$ adb shell start
当log.redirect-stdio
设置为true时,仍然没有从stdio到logcat的输出。
我也尝试使用streambuf
定制几个std::cout.rdbuf
实现来尝试使用__android_log_print
将stdout定向到logcat,但是这些都没有向logcat打印任何东西。
有没有人成功设法将stdout重定向到Android 5中的logcat?
如果需要,我可以添加更多细节(例如我尝试过的streambuf
实现)。
这对于将stdout重定向到logcat的问题并不是真正的解决方案,但我建议将其作为一种解决方法,以防它对某人有所帮助。
您可以将stdout重定向到文件:
freopen("/data/data/com.your.package/files/out.txt", "w", stdout);
... // Call GMock which prints to the file instead
fclose(stdout)
然后我们可以在cat
文件中查看记录的测试结果。可悲的是Android没有tail
所以日志记录实时不是很好。 (除非你擅长垃圾邮件cat
)
用旧的Java方式做到这一点:(但我使用的是kotlin,任何人都可以提出更清洁的版本吗?)
documentation: System.setOut()
import java.io.OutputStream
import java.io.PrintStream
private const val TAG = "MyActivity"
class LogcatOutputStream: OutputStream(){
private var line_buffer: StringBuilder = StringBuilder()
override fun write(b: Int){
when(b){
'\n'.toInt() -> {
Log.i(TAG, line_buffer.toString())
line_buffer.setLength(0)
}
else -> line_buffer.append(b.toChar())
}
}
}
// put this somewhere in the code, like onCreate() as shown
class MainActivity: Activity(){
override fun onCreate(savedInstanceState: Bundle?){
// some other code
PrintStream(LoggerOutputStream()).let{
System.setOut(it)
System.setErr(it)
}
// some other code
}
}
// result:
println("Hello World") // which is effectively System.out.println in Java
// with have the below output in logcat
I/MyActivity(<pid>): Hello World
// as a reminder, you can filter logcat by tags
adb logcat MyActivity:D
// to only show logs tagged with 'MyActivity' (same value as 'TAG' above)