log4j performance

前端 未结 7 1727
终归单人心
终归单人心 2021-01-08 01:18

I\'m developing a web app, and I\'d like to log some information to help me improve and observe the app. (I\'m using Tomcat6)

First I thought I would use StringBuild

7条回答
  •  春和景丽
    2021-01-08 01:38

    If performance is a concern, be sure to pay special attention to the pattern layout documentation and avoid expensive conversion characters such as C, F, L, and M. These require shenanigans to retrieve this info.

    In place of C, use c and appropriately name your Logger objects when they are created. This means you can't inherit loggers from parent classes, but the inconvenience of redefining the logger is worth the increase to performance. F, L, and M don't have easy replacements for their functionality, but well worded log messages should be really easy to find in your source, so the need to specify the exact method, file, and line is diminished.

    Finally, avoid dynamic string concatenation in your log messages. When it is necessary to use concatenation, be sure to wrap the creation of that logging string in the appropriate checker method.

    private final static Logger LOG = Logger.get(MyClass.class);
    ...
    void someMethod() {
        if (LOG.isDebugEnabled()) {
            LOG.debug("some really expensive string concatenation: " + someInstanceVariable + " a bunch of other text!");
        }
    }
    

    The isDebugEnabled() always runs in constant time. LOG.debug() itself essentially does a isDebugEnabled() check at the beginning, but the string passed as a parameter must be fully built before that check can happen, causing an unnecessary delay when debug level is turned off.

提交回复
热议问题