View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, 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,
31        StackTraceElement[] parentSTE) {
32  
33      StackTraceElement[] ste = t.getStackTrace();
34      final int numberOfcommonFrames = findNumberOfCommonFrames(ste, parentSTE);
35  
36      strList.add(formatFirstLine(t, parentSTE));
37      for (int i = 0; i < (ste.length - numberOfcommonFrames); i++) {
38        strList.add("\tat "+ste[i].toString());
39      }
40  
41      if (numberOfcommonFrames != 0) {
42        strList.add("\t... "+numberOfcommonFrames + " common frames omitted");
43      }
44  
45      Throwable cause = t.getCause();
46      if (cause != null) {
47        ThrowableToStringArray.extract(strList, cause, ste);
48      }
49    }
50  
51    private static String formatFirstLine(Throwable t,
52        StackTraceElement[] parentSTE) {
53      String prefix = "";
54      if (parentSTE != null) {
55        prefix = CoreConstants.CAUSED_BY;
56      }
57  
58      String result = prefix + t.getClass().getName();
59      if (t.getMessage() != null) {
60        result += ": " + t.getMessage();
61      }
62      return result;
63    }
64  
65    private static int findNumberOfCommonFrames(StackTraceElement[] ste,
66        StackTraceElement[] parentSTE) {
67      if (parentSTE == null) {
68        return 0;
69      }
70  
71      int steIndex = ste.length - 1;
72      int parentIndex = parentSTE.length - 1;
73      int count = 0;
74      while (steIndex >= 0 && parentIndex >= 0) {
75        if (ste[steIndex].equals(parentSTE[parentIndex])) {
76          count++;
77        } else {
78          break;
79        }
80        steIndex--;
81        parentIndex--;
82      }
83      return count;
84    }
85  
86  }