View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.helpers;
15  
16  import java.util.LinkedList;
17  import java.util.List;
18  
19  import ch.qos.logback.core.CoreConstants;
20  
21  public class ThrowableToStringArray {
22  
23      public static String[] convert(Throwable t) {
24          List<String> strList = new LinkedList<String>();
25          extract(strList, t, null);
26          return strList.toArray(new String[0]);
27  
28      }
29  
30      private static void extract(List<String> strList, Throwable t, StackTraceElement[] parentSTE) {
31  
32          StackTraceElement[] ste = t.getStackTrace();
33          final int numberOfcommonFrames = findNumberOfCommonFrames(ste, parentSTE);
34  
35          strList.add(formatFirstLine(t, parentSTE));
36          for (int i = 0; i < (ste.length - numberOfcommonFrames); i++) {
37              strList.add("\tat " + ste[i].toString());
38          }
39  
40          if (numberOfcommonFrames != 0) {
41              strList.add("\t... " + numberOfcommonFrames + " common frames omitted");
42          }
43  
44          Throwable cause = t.getCause();
45          if (cause != null) {
46              ThrowableToStringArray.extract(strList, cause, ste);
47          }
48      }
49  
50      private static String formatFirstLine(Throwable t, StackTraceElement[] parentSTE) {
51          String prefix = "";
52          if (parentSTE != null) {
53              prefix = CoreConstants.CAUSED_BY;
54          }
55  
56          String result = prefix + t.getClass().getName();
57          if (t.getMessage() != null) {
58              result += ": " + t.getMessage();
59          }
60          return result;
61      }
62  
63      private static int findNumberOfCommonFrames(StackTraceElement[] ste, StackTraceElement[] parentSTE) {
64          if (parentSTE == null) {
65              return 0;
66          }
67  
68          int steIndex = ste.length - 1;
69          int parentIndex = parentSTE.length - 1;
70          int count = 0;
71          while (steIndex >= 0 && parentIndex >= 0) {
72              if (ste[steIndex].equals(parentSTE[parentIndex])) {
73                  count++;
74              } else {
75                  break;
76              }
77              steIndex--;
78              parentIndex--;
79          }
80          return count;
81      }
82  
83  }