1

I have same issue which is answered in this post How do I print my Java object without getting "SomeType@2f92e0f4"? I am trying to print PutObjectRequest in logs which is printing object reference value. But, I can't add toString() method, as I'm using a predefined class (PutObjectRequest) from AWS. Is there any way to print what values going in that object?

log.info("Sending request: {}", request);
Community
  • 1
  • 1
GSR
  • 15
  • 1
  • 4
  • 1
    Not really. If the creators of that class didn't have the foresight to include a proper `toString()` method you're kind of boned. You could look up each object type in a list and select an appropriate pretty printer (that you have to write) but that's a fairly time consuming thing to implement. – markspace Jan 23 '17 at 03:23
  • The type might be able to be easily serialized to a format like JSON; if this is the case then some (useful or not) text might be relatively easily extractable.. YMMV and there are other potential issues here, depending on object graph. JSON serialization itself uses reflection, which /can/ be done manually. – user2864740 Jan 23 '17 at 03:24
  • Or you could just poke at it with reflection I guess. Also tedious, but you might be able to write one method that does a reasonable job of printing all of the objects in your system with no `toString()`. – markspace Jan 23 '17 at 03:33

1 Answers1

1

Is there any way to print what values going in that object?

You need to write your own method to extract the relevant components of the request objects (using the public getters), appropriately format them, and return the lot as a string. Then call that method on the request object, and pass the resulting string to the logger instead of the request object.

If you need to delve into the private state (using abstraction-smashing reflection), that is more difficult, and you risk having your code break if the implementation details of the request class change.

Tedious. But there isn't a general solution, AFAIK.

(If you use a generic serialization scheme, you are liable to run against the problem that some of the components are either not relevant, or nor serializable, or huge ...)


UPDATE - Actually, it would be advisable to use your custom method like this:

if (log.isInfoEnabled()) {
    log.info("Sending request: {}", myFormat(request));
}

If you don't guard the info(...) call, the overhead of formatting will be incurred irrespective of the loggin level.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216