View Javadoc

1   /**
2    * Logback: the generic, reliable, fast and flexible logging framework.
3    * 
4    * Copyright (C) 2000-2008, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  
11  package ch.qos.logback.classic.spi;
12  
13  import java.util.LinkedList;
14  import java.util.List;
15  
16  import ch.qos.logback.core.CoreConstants;
17  
18  /**
19   * Convert a throwable into an array of ThrowableDataPoint objects.
20   * 
21   *  
22   * @author Ceki Gülcü
23   */
24  public class ThrowableToDataPointArray {
25  
26    static final ThrowableDataPoint[] TEMPLATE_ARRAY = new ThrowableDataPoint[0];
27  
28    
29    static public ThrowableDataPoint[] convert(Throwable t) {
30      List<ThrowableDataPoint> tdpList = new LinkedList<ThrowableDataPoint>();
31      extract(tdpList, t, null);
32      return tdpList.toArray(TEMPLATE_ARRAY);
33    }
34  
35    static private void extract(List<ThrowableDataPoint> tdpList, Throwable t,
36        StackTraceElement[] parentSTE) {
37      StackTraceElement[] ste = t.getStackTrace();
38      final int numberOfcommonFrames = STEUtil.findNumberOfCommonFrames(ste, parentSTE);
39  
40      tdpList.add(firstLineToDataPoint(t, parentSTE));
41      for (int i = 0; i < (ste.length - numberOfcommonFrames); i++) {
42        tdpList.add(new ThrowableDataPoint(ste[i]));
43      }
44      
45      if (numberOfcommonFrames != 0) {
46        tdpList.add(new ThrowableDataPoint("\t... "+numberOfcommonFrames
47            + " common frames omitted"));
48      }
49  
50      Throwable cause = t.getCause();
51      if (cause != null) {
52        extract(tdpList, cause, ste);
53      }
54    }
55  
56    private static ThrowableDataPoint firstLineToDataPoint(Throwable t,
57        StackTraceElement[] parentSTE) {
58      String prefix = "";
59      if (parentSTE != null) {
60        prefix = CoreConstants.CAUSED_BY;
61      }
62  
63      String result = prefix + t.getClass().getName();
64      if (t.getMessage() != null) {
65        result += ": " + t.getMessage();
66      }
67      return new ThrowableDataPoint(result);
68    }
69  
70   
71  
72  }