Java - Get position in code (package / class / method)

OK, maybe a stupid question. I am working on a java project, and I want to be able to easily get the position of my current code, namely Package / Class / Method, and print it for output.

For example, I want to display information about a package / class / method in cases with an error in order to be able to recognize the exact method in which the error occurs.

Is there any code that can give me this information?

+3
source share
3 answers

You will have stacktraceon JVMit contains all this information, just register it.

Or programmatically if you want to define

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

According to Javadocs :

[...] , . , .

A StackTraceElement getClassName(), getFileName(), getLineNumber() getMethodName().

+4

, . , exception.printstacktrace(); .

, ​​ log4j, logger.error( "message", exception );, .

+4

.

log4j, . , :% -5p% d [% t]% C {1}.% M (% L):% m% n

% t is the current thread% C {1} is the class name (omit {1} and you will get the fully qualified name with the package)% M is the method name% L is the line number for any details here: http: // logging .apache.org / log4j / 1.2 / apidocs / org / apache / log4j / PatternLayout.html

Keep in mind that a method name or line number degrades performance. Never do this in a production system.

+2
source

Source: https://habr.com/ru/post/1789450/


All Articles