Question

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)?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top