If there was a slow way to get this information programmatically, log4j would use it, unfortunately, not, because this is not information that the JVM was designed to make it accessible to the runtime.
That's why most logging protocols use only templates that extract this information at the debug level and then wrap all debug calls in the if(logger.isDebugEnabled()) { state, so that information is only retrieved when the program is in debug mode. This approach allows you to get fine-grained information about the runtime during debugging without affecting the performance of your code when it is in production.
It is also important to remember that not all code has high performance, and if your code works and scales using these templates, you can simply use them. If you run into performance issues, you can review.
Aside, Groovy (starting from version 1.8) has AST transformations that automatically insert registrars (from java.util, apache commons, log4j or flf4j flavors) into your classes, and also automatically complete all recording calls in conditions at compile time, so that they are executed only when logging is at an appropriate level. This means that you can do what I described above without having to explicitly code conditional expressions, but, of course, is only available if you're writing Groovy.
Johansensen
source share