0

I want to have a method to quickly dump detailed information to a log. It'll be something like this:

public static void log(String message, Class<?> sourceClass){
    dump(formattedTime+sourceClass.getName()+"line"+lineNumberfromwhichthemessagecomes 
    (if several occurences are found, show all of them if there's no other way to
    detectwhere has the method been called from).
}

I already know that trick about creating a new Exception object and getting the line number of the first line of its stack trace, but by using that I would have to add the line number as a parameter because if you do the trick inside the log method, you will always get the same line number (the one of the line you make the trick in).

Is there any way to achieve this)?

  • 2
    Couldn't you do get the second line in stead of the first, and take that linenumber? Than you could keep your logic within the logger itself. – Derk Sep 22 '12 at 14:29
  • 1
    You should not be using exceptions at all. Thread.currentThread().getStackTrace() avoids the costly exceptions and gives you the same stack information. – Bananeweizen Sep 22 '12 at 16:37

1 Answers1

6

You can use Exception's getStackTrace() method to get a list of the stack frames. Then you can move up the stack either by 1 element or using some logic (e. g. until you get a method that's not in your logging class) and use the line number from that StackTraceElement for your logging.

ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152