user1487380
user1487380

Reputation: 362

Logging log4j and Null object

I wonder that can I avoid NullPointerException in _log.info. I have 1 null object (obj) and then

_log.info("obj id: " + obj.objId());

In this case I want _log printout that obj.objId() is null and not throw an exception :-? anyone know how to ?

Upvotes: 0

Views: 11349

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347204

That's not an issue with log4j, that's an issue with your program

You could do something along the lines of ....

_log.info("obj id: " + (obj == null ? null : obj.objId()));

I don't think the problem is that the ID is null, I think, from what you are saying, the obj is null, thus the reference to obj.objId() is causing the NPE

Upvotes: 2

D.Shawley
D.Shawley

Reputation: 59563

What about: _log.info(String.format("obj id: %s", (obj == null ? obj : obj.objId())));?

Upvotes: 1

Related Questions