Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define macro to log error with file and line in android

I want to make a Error Log that throw in what file and line the problem is using . But I didn't find a good reference. All code is using JNI, C++ side.

This Try fail:

#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR  , LOG_TAG,"%s %s %s",__VA_ARGS__, __FILE__, __LINE__)

This one only show the msg, no the file and line

#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR  , LOG_TAG,__VA_ARGS__, __FILE__, __LINE__)

How could I print all the info clearly? Is possible to print only some arguments from __VA_ARGS__, something like __VA_NARG__ ? Extra info or useful references for this kind of things?

like image 559
vgonisanz Avatar asked Oct 15 '13 07:10

vgonisanz


1 Answers

Very interesting and useful question! I found this solution, which may not be the simplest, but works for me:

#define LOGE(x...) do { \
  char buf[512]; \
  sprintf(buf, x); \
  __android_log_print(ANDROID_LOG_ERROR,"TAG", "%s | %s:%i", buf, __FILE__, __LINE__); \
} while (0)

This line:

LOGE("Test: %i", 42)

logs the following:

TAG    Test: 42 | path/to/file.cpp:line

Beware of the arbitrary 512 length of the buffer if you intend to log longer things!

Hope this helps!

like image 109
mbrenon Avatar answered Oct 09 '22 07:10

mbrenon