Thursday, April 5, 2018

when logger crashed the application

Ever heard a logging statement causing out of memory crashes in an application.

Some technical details: (Though most of the folks stopping by should already know, but I talked to few techi folks who weren't aware about it)

When you write
logger.debug("got a request to execute"); // We are good.

But when you write

logger.debug(heavyObject.toString());       // or
logger.debug("some string" + "some string" + someHeavyObject);

your application (and common sense) goes down the hill. 




One will argue that heavy operation will happen only if log level is debug. 
But that's wrong. Because, even before the flow reaches inside 'logger.debug', the object transformation is done. No, this is not because your logging library is bad, but because that's how Java is, and even most of the other languages. That's the way its suppose to be.

So please guard the heavy logging statements with log level check.
if (logger.level==debug) {
       logSomeHeavyStuff();
}

Yes that's ugly but that will save your application some precious CPU and memory.

Recently the project I was working on, was getting OutOfMemory crashes. That's what happen when you try to convert a 60,000 object array into a string for a trace level debugging. :)

Why that object grew to 60K, is another story to be told some other day.