On Android, you can output the log by writing Log.d (TAG," some log text ... ")
, but it was troublesome to declare the TAG
variable every time, so depending on the caller. I thought it would be convenient if the file name and line number were automatically acquired and TAG
was set. ** It's done. ** Create a class in Texto and create a method like the following. Let's call it the Logger
class.
Logger.java
public class Logger {
public static void log(String text) {
StackTraceElement elem = Thread.currentThread().getStackTrace()[2];
String tag = elem.getFileName();
Log.d(tag, text);
}
}
Then call this method where you want to spit out the log.
Logger.log("hello world");
Output example
09-15 19:52:03.270 15378-15378/com.niusounds.myapps D/MainActivity.java: hello world
Easy! !!
By the way, calling the same code from Kotlin gave different results. In the case of Kotlin, it seems that you have to get Thread.currentThread (). StackTrace [3]
.
Log.kt
fun log(text: String) {
val caller = Thread.currentThread().stackTrace[3]
val tag = "${caller.fileName}:${caller.lineNumber}"
Log.d(tag, text)
}
Recommended Posts