Glide
Glide

Reputation: 21245

Need help understanding Logback's parameterized logging optimization

The logback parameterized logging docs says:

Object entry = new SomeObject();
logger.debug("The entry is {}.", entry);

Only after evaluating whether to log or not, and only if the decision is positive, will the logger implementation format the message and replace the {} pair with the string value of entry. In other words, this form does not incur the cost of parameter construction when the log statement is disabled.

My interpretation of that is that entry won't be evaluated at all if the logger is set to DEBUG. But how is that possible?

In other words, if I wrote:

logger.debug("the entry is {}.", dbService.getEntry());

I assume dbService.getEntry() won't be called if the logger is not set to DEBUG. Is my understanding correct?

Upvotes: 0

Views: 270

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

That statement means that construction of the formatted message, including the expense of calling toString() on entry occurs only if the log level is enabled. The choice of words "parameter construction" is misleading. It refers to assembly of the formatted message only.

If your code performs an expensive operation to construct the value passed to the logger then you will incur the expense every time whether or not the log level is enabled. For instance

logger.debug("The entry is {}.", entry.someVeryExpensiveOperation());

This is standard Java, nothing magic happens. someVeryExpensiveOperation() gets invoked every time.

Upvotes: 4

Related Questions