Daanish
Daanish

Reputation: 1091

Logging line numbers of the java code which has executed

I am developing an application. As a part of this, when the Java program executes, we want to display line numbers of the source of the Java program where the code has executed. I'm using the Code class to get the line number of the methods in the code. But I want to get the line number of the source that have been executed,that is ,code path.

I will add to this, the program I have written to display the line numbers of the methods.

class LineNum
{
  LineNumber[] ln = new LineNumber[300];
  JavaClass clazz ;
  Code classinfo ;

  public static void printCode(Method[] methods) {
    System.out.println("Entering PrintCode");
    for(int i=0; i < methods.length; i++) {
      System.out.println(methods[i]);

      Code code = methods[i].getCode();
      if(code != null) // Non-abstract method
      {  
        System.out.println(code.getLineNumberTable());
      }
    }
  }
  public static void main(String[] args) {
    LineNum liner = new LineNum();
    liner.clazz = Repository.lookupClass("package_name.File_name");
    printCode(liner.clazz.getMethods());
  }
}

Upvotes: 1

Views: 2931

Answers (3)

Don
Don

Reputation: 1144

You can call

StackTraceElement[] ele = Thread.currentThread().getStackTrace()

an any time which gives you the previously calls. The StackTraceElement class has a method getLineNumer() to get the line number.

http://docs.oracle.com/javase/7/docs/api/java/lang/StackTraceElement.html

Upvotes: 2

kodstark
kodstark

Reputation: 490

I think that using lo4j is best solution (how it is described by @bazwilliams). Code is depended on simple library and logging line numbers can be optional configured outside of code.

@bazwilliams - you can configure layout pattern only for selected logging category (thus configuring selected appender).

PS. I answered because I didn't know how to comment @bazwilliams answer (or I couldn't).

Upvotes: 1

bazwilliams
bazwilliams

Reputation: 330

If you use Log4J as your logging library, you can configure it to output the line number as part of the pattern. See 'PatternLayout' and the 'L' conversion pattern character.

You could use a conversion pattern like: "%-5p [%t](%L): %m%n" to yield:

   DEBUG [main](103): Message 1
   WARN  [main](104): Message 2

PatternLayout API: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

Upvotes: 2

Related Questions