Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android,NDK, write logs to a file

I have this lines in my code (.c) :

#define LOGI(x...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG,x)
#define LOGE(x...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,x)

I use them for outputing in LogCat, how to modify these lines to write messages to a file, or how can I get certain messages from LogCat in my code ? Thanks in advance.

like image 672
Mickey Tin Avatar asked May 01 '26 16:05

Mickey Tin


1 Answers

If this is for debugging purpose, I use this macro:

#define WRITE_LOG(s, ...) do { \
FILE *f = fopen("/data/local/tmp/log.txt", "a+"); \
  fprintf(f, s, __VA_ARGS__); \
  fflush(f); \
  fclose(f); \
} while (0)

It has the advantage of being totally independent from the Android SDK/NDK, which allows to debug native code without having to modify all your build system and includes in order to link on the logcat functions.

A small warning though: I've taken the habit of creating the file using touch /data/local/tmp/log.txt in adb-shell before launching the program, as in most cases the system prevents you from creating new files. And by the way, the location /data/local/tmp/ has the advantage of being accessible even without root privileges.

like image 131
mbrenon Avatar answered May 03 '26 07:05

mbrenon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!