Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4j: fastest way to display method name?

In my logging messages, I need to insert the name of the method where the messages were produced. I've looked at Log4J documentation and "M" and "l" conversion chars that also have warning like "WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue". So I have (at least) two options:

  1. Use these chars but slow down my code
  2. Manually insert method name into messages, i.e. something like this log.info("myMethod: message"); which will be faster but not as elegant

Are there any other options that would not slow down my code?

Thanks!

like image 560
I Z Avatar asked Apr 02 '12 15:04

I Z


2 Answers

I am not sure of the IDE that you are using, but if you are using Eclipse based IDE's you should be able to use some Java templates. This will still be using the method names as strings,but will save you typing time.

I created a whole set of templates like this:

  • Template name - li
  • Pattern - logger.info("${cursor}");

and so on for warn, error, and debug.

For start and end of method, or just to add method name to every log out - use something like:

  • Template name - lie
  • Pattern - logger.info("End: ${enclosing_method}${cursor}");

and so on.

The only constraint is your logger ref variable will always have to be named logger. Now you will just need to type lie and (optionally hit ctrl+space if you uncheck the Automatically Insert checkbox at template creation time.)

HTH!

like image 155
Abhi Avatar answered Oct 11 '22 02:10

Abhi


I use the basic configurator most of the times and it gives me the method name by default. So technically adding just this single line of code and the import statement is the fastest way to get what you are asking for.

BasicConfigurator.configure();
like image 2
Risav Karna Avatar answered Oct 11 '22 00:10

Risav Karna