View Javadoc

1   package org.lsst.ccs.utilities.logging;
2   
3   /**
4    * manages formatting of stackTrace.
5    * @implNote
6    * For the time being there is a global depth of StackTrace for all formatters that use
7    * the static <TT>toString</TT> method.
8    * HTis could be changed in the future and we my have a different depth for each <TT>Formatter</TT>
9    * @author bamade
10   */
11  // Date: 15/04/2014
12  
13  public class StackTraceFormats {
14      private static int depth = -1;
15      private static volatile boolean modified = false;
16  
17      public static int getDepth() {
18          return depth;
19      }
20  
21      public static void setDepth(int depth) {
22          StackTraceFormats.depth = depth;
23          modified = true;
24      }
25  
26      public static void setDepthFromInitialProperties() {
27          if (modified) return;
28          int depth = LogPropertiesLoader.loaderGetIntProperty("org.lsst.ccs.logging.StackTraceFormats.depth", -1);
29          setDepth(depth);
30  
31      }
32  
33      /**
34       * formats the StackTrace of a <TT>Throwable</TT>.
35       * @param throwable
36       * @return
37       */
38      public static String toString(Throwable throwable) {
39          return toString(throwable,1) ;
40      }
41  
42      /**
43       * recursive method to format a <TT>Throwable</TT>
44       * @param throwable
45       * @param level is 1 the first time then incremented each time an additional level of recursion is added
46       * @return
47       */
48      public static String toString(Throwable throwable, int level) {
49          StringBuilder stb = new StringBuilder(String.valueOf(throwable)).append('\n');
50          StackTraceElement[] traces = throwable.getStackTrace();
51          int size = traces.length;
52          if ((depth < 0) || (size <= (depth * 2))) {
53              for (StackTraceElement trace : traces) {
54                  indent(stb, level).append(trace).append('\n');
55              }
56  
57          } else {
58              for (int ix = 0; ix < depth; ix++) {
59                  indent(stb, level).append(traces[ix]).append('\n');
60              }
61              indent(stb, level).append(".....\n");
62              for (int ix = size - (depth); ix < size; ix++) {
63                  indent(stb, level).append(traces[ix]).append('\n');
64              }
65          }
66          Throwable cause = throwable.getCause();
67          if (cause != null) {
68              indent(stb, level - 1).append("caused by : ").append(toString(cause, level + 1));
69          }
70          return stb.toString();
71      }
72  
73      private static StringBuilder indent(StringBuilder stb, int level) {
74          for (int ix = 0; ix <= level; ix++) {
75              stb.append("  ");
76          }
77          return stb;
78      }
79  }