Log, log, log

Most common pattern, when doing logging, is currently this:


Some could say, that these checks “blow” up the code… But what if the LEVEL(…) call itself would check the “isLEVEL()” ? The code would be a little bit cleaner, isn’t it ?


Our internal logger does this, and I ran into the pitfall 🙂 But we still do (sometimes) check for the log_level, before calling logger.LEVEL(), like here:

StringBuffer sb = .....;
logger.LEVEL(sb.toString(), theCaughtException);

These if statements are made just to avoid unneeded object creation or other more “heavy” tasks.



Posted in java
4 comments on “Log, log, log
  1. log4j is doing this selfcheck internally, use it.

  2. Unfortunately doing the check inside is really not what you want. The problem with


    is that the objects to construct the log line (the “….”) will be created no matter what. So the above will create significantly more String objects.

    A printf style API will just create one format string. This is why with slf4j you don’t necessarily have to use the if-wrapper. Another option is to have the build system add the wrapping if with just4log.

    I usually just wrap DEBUG but not INFO and ERROR.

  3. matthiaswessendorf says:

    LOGGER.fine(“foo”) does not create a new String object. The “foo” is stored in the class definition and when the class is loaded, “foo” is loaded, interned, and the references replaced with pointers to the shared instance.

  4. but LOGGER.fine(“test” + something) does …and I guess that’s you will be doing most of the time there 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: