When we record logs, each class will define a log object and then use this object to write logs. When we process logs, how can I record the class, method, and row number of a log object? How does log4j implement this function? In fact, we can get the current thread information when writing the Log Code, so that we can get the information of the previous thread (that is, the information of the class where the object writes the log ). First look at the following columns. Create Location class and Test class: Location: [java] public class Location {public void getInfo () {String location = ""; StackTraceElement [] stacks = Thread. currentThread (). getStackTrace (); location = "Class Name:" + stacks [2]. getClassName () + "\ n function name:" + stacks [2]. getMethodName () + "\ n file name:" + stacks [2]. getFileName () + "\ n row number:" + stacks [2]. getLineNumber () + ""; System. out. println (location) ;}} Test: [java] public class Test {pu Blic static void main (String [] args) {Location l = new Location (); l. getInfo () ;}} executes the main function in Test and returns the following result: [java] Class Name: thread. test function name: main file name: Test. java line number: 10 does it output the call information in the Test class? So many people have asked why the location class calls stacts [2] instead of stacts [0] or others? To solve this problem, we can traverse the content in the stacts array and output it as soon as possible: [java] StackTraceElement [] stacks = Thread. currentThread (). getStackTrace (); for (int I = 0; I <stacks. length; I ++) {location = I + "at" + stacks [I]. getClassName () + ". "+ stacks [I]. getMethodName () + "(" + stacks [I]. getFileName () + ":" + stacks [I]. getLineNumber () + ")"; System. out. println (location);} run again. The output is as follows: [java] 0 at java. lang. thread. getStackTrace (Thread. java: 1436) 1 at thread. location. getInfo (Location. java: 6) 2 at thread. test. main (Test. java: 7) This is easy to understand. The Thread is stored in the stack form. Analyze StackTraceElement [] stacks = Thread. currentThread (). getStackTrace (); this Code creates two threads and calls the Thread. currentThread (). when getStackTrace () is used, a thread is created at the underlying layer, and we call it to create a thread. Then, test creates a thread when calling the getInfo function, so that there are three threads in total, the program execution sequence is to call the getInfo method in the test class first, and then call StackTraceElement [] stacks = Thread in the getInfo method. currentThread (). getStackTrace (); Call S TackTraceElement [] stacks = Thread. currentThread (). getStackTrace (); a thread will be created at the underlying layer. According to the stack principle, the queuing sequence is the result output above.