How to write caller location information to a log file using Java without sacrificing performance?

How can I write caller location information (source file and Java string) in a log file using Java and log4j, but without sacrificing performance? log4j allows you to write such information to a log file, but it uses a stack trace to retrieve this information each time a log report is issued, resulting in poor performance. I am looking for alternative performance, such as getting location information at compile time rather than run time. Can annotations be used for this? Or maybe some other technique?

+3
source share
2 answers

How to make it part of the build process for the replacement of certain fillers, such as $filename$, and $linenumber$in this passage.

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

To replace the file name, you may need to replace the keyword with your version control system. Disclaimer: this is just from the head, I never tried it myself.

+1
source

I agree with Rob that this is not necessary at all. Usually in the log message there is some separate line, looking for it will get into the source code. With a good IDE, this is very fast.

Now, given the question as is, this is a possible solution:

Class Foo
    void bar()
        new Logger(){} . warn("blah");

for each log action at run time, a new object is created - this is not a problem.

, , . .

:

abstract public class Logger
    static Map<Class, String> sourceInfo = new ...
    public Logger()
        Class thisClass = this.getClass();
        String info = sourceInfo.get(thisClass);
        if(info==null)
             info = ... // init from stack trace
             sourceInfo.put(thisClass,info)
        this.info = info

     public void warn(msg)
        log(WARN, this.info,msg)
0

Source: https://habr.com/ru/post/1761990/


All Articles