简体   繁体   中英

Print object ids in logback log or stacktrace in java

Is there any way to get Java or Logback to give my the object id (or address or whatever) in stack traces and log calls. In other words, instead of this:

com.example.MyObject

in my stack traces I want this:

com.example.MyObject@123456

And for logging, I want this:

LOG.debug("A message");

to act like this:

LOG.debug(this + ": A message");

I can't see a way to do it though, because both Logback and java itself seem to use StackTraceElement s, and those don't record this information.

For bonus points, how is Object.toString() implemented in dalvik? The generic java docs say it is toHex(Object.hashCode()) but I tested that and it doesn't match.

As you note, stack traces per se don't contain references to the this in each frame. That info is available, though, to a debugger. There is probably a hacky way to get the info you want, but it'd be ugly, slow, and probably flaky. Honestly, I wouldn't bother.

For bonus points, how is Object.toString() implemented in dalvik?

Here's (something like) tip-of-tree of Object.java : https://android.googlesource.com/platform/libcore/+/bcf0a81a927992883f0cb49c1c945141d1261b8b/luni/src/main/java/java/lang/Object.java

From there:

public String toString() {
    return getClass().getName() + '@' + Integer.toHexString(hashCode());
}

Note that this is the base implementation in the class Object , but it is commonly overridden in subclasses. This may explain whatever difference you may have seen.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM