Search code examples
performancemethodslog4j

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!


Solution

  • 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!