001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.log4j; 018 019import org.apache.log4j.spi.ThrowableRenderer; 020 021import java.io.StringWriter; 022import java.io.PrintWriter; 023import java.io.LineNumberReader; 024import java.io.StringReader; 025import java.io.IOException; 026import java.io.InterruptedIOException; 027import java.util.ArrayList; 028 029/** 030 * Default implementation of ThrowableRenderer using 031 * Throwable.printStackTrace. 032 * 033 * @since 1.2.16 034 */ 035public final class DefaultThrowableRenderer implements ThrowableRenderer { 036 /** 037 * Construct new instance. 038 */ 039 public DefaultThrowableRenderer() { 040 041 } 042 043 044 /** 045 * {@inheritDoc} 046 */ 047 public String[] doRender(final Throwable throwable) { 048 return render(throwable); 049 } 050 051 /** 052 * Render throwable using Throwable.printStackTrace. 053 * @param throwable throwable, may not be null. 054 * @return string representation. 055 */ 056 public static String[] render(final Throwable throwable) { 057 StringWriter sw = new StringWriter(); 058 PrintWriter pw = new PrintWriter(sw); 059 try { 060 throwable.printStackTrace(pw); 061 } catch(RuntimeException ex) { 062 } 063 pw.flush(); 064 LineNumberReader reader = new LineNumberReader( 065 new StringReader(sw.toString())); 066 ArrayList lines = new ArrayList(); 067 try { 068 String line = reader.readLine(); 069 while(line != null) { 070 lines.add(line); 071 line = reader.readLine(); 072 } 073 } catch(IOException ex) { 074 if (ex instanceof InterruptedIOException) { 075 Thread.currentThread().interrupt(); 076 } 077 lines.add(ex.toString()); 078 } 079 String[] tempRep = new String[lines.size()]; 080 lines.toArray(tempRep); 081 return tempRep; 082 } 083}