aboutsummaryrefslogtreecommitdiff
path: root/third_party
diff options
context:
space:
mode:
authorJinghao Shi <jhshi@users.noreply.github.com>2017-08-21 11:42:49 -0700
committerAng Li <angli@google.com>2017-08-21 11:42:49 -0700
commit346bb72684eb114f6cd3a6093e1a6872d90b69ba (patch)
treeae08f8833fe8d7e579cf1bbc5d66119d03c9cd17 /third_party
parentaca997a8dd6e6b84cc019b8d083bb35e796080f0 (diff)
downloadmobly-snippet-lib-346bb72684eb114f6cd3a6093e1a6872d90b69ba.tar.gz
Better way to find the name of the calling class of logger (#70)
Walk stack instead of hard-coded depth
Diffstat (limited to 'third_party')
-rw-r--r--third_party/sl4a/src/main/java/com/google/android/mobly/snippet/util/Log.java32
1 files changed, 28 insertions, 4 deletions
diff --git a/third_party/sl4a/src/main/java/com/google/android/mobly/snippet/util/Log.java b/third_party/sl4a/src/main/java/com/google/android/mobly/snippet/util/Log.java
index c68631a..b5b1d9b 100644
--- a/third_party/sl4a/src/main/java/com/google/android/mobly/snippet/util/Log.java
+++ b/third_party/sl4a/src/main/java/com/google/android/mobly/snippet/util/Log.java
@@ -25,6 +25,9 @@ import android.os.Bundle;
public final class Log {
public static volatile String APK_LOG_TAG = null;
+ private static final String MY_CLASS_NAME = Log.class.getName();
+ private static final String ANDROID_LOG_CLASS_NAME = android.util.Log.class.getName();
+
private Log() {}
public static synchronized void initLogTag(Context context) {
@@ -56,10 +59,31 @@ public final class Log {
throw new IllegalStateException("Logging called before initLogTag()");
}
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
- String fullClassName = stackTraceElements[4].getClassName();
- String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
- int lineNumber = stackTraceElements[4].getLineNumber();
- return logTag + "." + className + ":" + lineNumber;
+
+ boolean isCallerClassNameFound = false;
+ String fullClassName = null;
+ int lineNumber = 0;
+ // Walk up the stack and look for the first class name that is neither us nor
+ // android.util.Log: that's the caller.
+ // Do not used hard-coded stack depth: that does not work all the time because of proguard
+ // inline optimization.
+ for (StackTraceElement element : stackTraceElements) {
+ fullClassName = element.getClassName();
+ if (!fullClassName.equals(MY_CLASS_NAME) &&
+ !fullClassName.equals(ANDROID_LOG_CLASS_NAME)) {
+ lineNumber = element.getLineNumber();
+ isCallerClassNameFound = true;
+ break;
+ }
+ }
+
+ if (!isCallerClassNameFound) {
+ // Failed to determine caller's class name, fall back the the minimal one.
+ return logTag;
+ } else {
+ String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
+ return logTag + "." + className + ":" + lineNumber;
+ }
}
public static void v(String message) {