简体   繁体   English

在Java中的logback日志或stacktrace中打印对象ID

[英]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. 有什么方法可以使Java或Logback在堆栈跟踪和日志调用中为我提供对象ID(或地址等)。 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. 但是,我看不到任何方法,因为Logback和Java本身似乎都使用StackTraceElement ,而这些都没有记录此信息。

For bonus points, how is Object.toString() implemented in dalvik? 对于奖励积分,如何在dalvik中实现Object.toString() The generic java docs say it is toHex(Object.hashCode()) but I tested that and it doesn't match. 通用的Java文档说它是toHex(Object.hashCode())但我对此进行了测试,但不匹配。

As you note, stack traces per se don't contain references to the this in each frame. 如您所述,堆栈跟踪本身在每个帧中都不包含this引用。 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? 对于奖励积分,如何在dalvik中实现Object.toString()

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 这是(类似) Object.javahttps : 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. 请注意,这是Object类中的基础实现,但通常在子类中将其重写。 This may explain whatever difference you may have seen. 这可以解释您所看到的任何差异。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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