문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top