0

Is there a way to assign unique id for every Java stack trace which appears after some exception? I would like to to get the number and use it for faster troubleshoot.

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • What about this: https://stackoverflow.com/questions/222108/getting-the-java-thread-id-and-stack-trace-of-run-away-java-thread – xsami Mar 02 '18 at 17:20
  • Not clear what you are looking for. Would some kind of hash value suffice? – Henry Mar 02 '18 at 17:20
  • @Henry yes, unique hash value which will be printed for every error stack into the log will be enough – Peter Penzov Mar 02 '18 at 17:22
  • You would need to do some experiments, but it should not be too hard to write a hash function that hashes the information which is important for you. – Henry Mar 02 '18 at 17:27
  • For faster 'trouble shooting' you are pursuing the wrong solution, use a logging framework to report the program state along with file and line numbers. e.g. log4j. – Martin Spamer Mar 02 '18 at 18:21
  • You could just maintain a counter, catch every exception and repack it to a custom exception with the current counter value and the original exception attached. Then increase the counter. – Zabuzard Mar 02 '18 at 18:52
  • Please select my answer as correct if it solves your question, thanks. – java-addict301 Mar 07 '18 at 23:40

1 Answers1

2

Why not just create a custom Exception and hash the stacktrace and set it as a unique id?

import org.apache.commons.lang.exception.ExceptionUtils;

public class MyException extends Exception {
    private static final long serialVersionUID = -2145930259049207199L;

    private final int uniqueId;

    public MyException(String message) {
        super(message);
        this.uniqueId = ExceptionUtils.getStackTrace(this).hashCode();
    }

    public int getUniqueId() {
        return uniqueId;
    }

}

If you want a truly unique id for each message (i.e. you're not trying to track duplicate exeption message), you can just set uniqueId in the constructor accordingly intead:

this.uniqueId = UUID.randomUUID().toString();
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
java-addict301
  • 3,220
  • 2
  • 25
  • 37
  • Do note though: hashCodes are not unique, and different hash codes can (and will for longer strings) collide with each other. – M. Prokhorov Mar 02 '18 at 18:38
  • Very true, however I'm guessing that's what he wants (to track duplicate exceptions occurring). If he wants one unique, then he could just set uniqueId = UUID.randomUUID().toString() – java-addict301 Mar 02 '18 at 18:40
  • 1
    Note that this solution uses the **Apache** library, its not plain Java. – Zabuzard Mar 02 '18 at 18:54