vgonisanz vgonisanz - 1 year ago 87
Android Question

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
, something like
Extra info or useful references for this kind of things?

Answer Source

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!