10

Is there any way to print file line number with android Log ?

enter image description here

Mithun Sreedharan
  • 49,883
  • 70
  • 181
  • 236
  • 1
    Refer discussion on this thread: http://stackoverflow.com/questions/115008/how-can-we-print-line-numbers-to-the-log-in-java – Nitin Oct 13 '11 at 05:52
  • Check this thread and Michael Baltaks answer, it might help you. http://stackoverflow.com/questions/115008/how-can-we-print-line-numbers-to-the-log-in-java – sat Oct 13 '11 at 05:54

4 Answers4

14

for getting line number `

public static int getLineNumber() {
    return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
or 
Thread.currentThread().getStackTrace()[2].getLineNumber()
 in Log()

` try it will help u....

Jigar Patel
  • 436
  • 4
  • 9
3

Better Logging In Android Using Timber with Log Line Number

In /app/build.gradle file

implementation 'com.jakewharton.timber:timber:4.7.1'

In Application class

Timber.plant(new Timber.DebugTree() {
                @Override
                protected @Nullable String createStackElementTag(@NotNull StackTraceElement element) {
                    return super.createStackElementTag(element) + ":"+element.getLineNumber();
                }
            });
Shomu
  • 2,734
  • 24
  • 32
1
object Logg {
  private fun tag(): String? {
    return Thread.currentThread().stackTrace[4].let {
      val link = "(${it.fileName}:${it.lineNumber})"
      val path = "App# ${it.className.substringAfterLast(".")}.${it.methodName}"
      if (path.length + link.length > 80) {
        "${path.take(80 - link.length)}...${link}"
      } else {
        "$path$link"
      }
    }
  }

  fun v(msg: String?) {
    Log.v(tag(), " $msg")
  }

  fun d(msg: String?) {
    Log.d(tag(), " $msg")
  }

  fun i(msg: String?) {
    Log.i(tag(), " $msg")
  }

  fun w(msg: String?) {
    Log.w(tag(), " $msg")
  }

  fun w(e: Throwable?) {
    Log.w(tag(), " ${e?.localizedMessage}")
    e?.printStackTrace()
  }

  fun w(e: Exception?) {
    Log.w(tag(), " ${e?.localizedMessage}")
    e?.printStackTrace()
  }
  
  fun w(e: LinkageError?) {
    Log.w(tag(), " ${e?.localizedMessage}")
    e?.printStackTrace()
  }

  fun e(msg: String?) {
    Log.e(tag(), " $msg")
  }

  fun e(e: Throwable?) {
    Log.e(tag(), " ${e?.localizedMessage}")
    e?.printStackTrace()
  }

  fun e(e: java.lang.Exception?) {
    Log.e(tag(), " ${e?.localizedMessage}")
    e?.printStackTrace()
  }
}
Hun
  • 3,652
  • 35
  • 72
0

To accomplish that, here is what I did (the %L outputs line number) :

## log4j.properties
log4j.rootLogger=DEBUG, CA

log4j.appender.CA=org.apache.log4j.ConsoleAppender

log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x (%F:%L) - %m%n
djangofan
  • 28,471
  • 61
  • 196
  • 289