Search code examples
javaperformancelogginglog4j

How to write caller location information in a log file using Java, without hurting performance?


How can I write caller location information (Java source file and line), in a log file using Java and log4j, but without hurting performance? log4j allow you to write such information in the log file, but it uses the stack trace to get that it information, every time a log statement is issued, what causes performance degradation. I'm looking for a performance friendly alternative, like getting the location information at compile time instead at runtime. It is possible to use annotations to accomplish that? Or maybe some other technique?


Solution

  • How about making it part of the build process to replace certain placeholders, like $filename$ and $linenumber$ in this snippet.

    logger.info("The original message... $filename$ $linenumber$");
    

    To replace the filename, it may suffice to have keyword substitution with your revision control system. Disclaimer: this is just from the top of my head, I never tried it myself.