001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.pattern;
015
016import ch.qos.logback.classic.spi.IThrowableProxy;
017import ch.qos.logback.classic.spi.ThrowableProxyUtil;
018import ch.qos.logback.core.CoreConstants;
019
020/**
021 * @author Tomasz Nurkiewicz
022 * @since 0.9.30
023 */
024public class RootCauseFirstThrowableProxyConverter extends ExtendedThrowableProxyConverter {
025
026    @Override
027    protected String throwableProxyToString(IThrowableProxy tp) {
028        StringBuilder buf = new StringBuilder(BUILDER_CAPACITY);
029        recursiveAppendRootCauseFirst(buf, null, ThrowableProxyUtil.REGULAR_EXCEPTION_INDENT, tp);
030        return buf.toString();
031    }
032
033    protected void recursiveAppendRootCauseFirst(StringBuilder sb, String prefix, int indent, IThrowableProxy tp) {
034        if (tp.getCause() != null) {
035            recursiveAppendRootCauseFirst(sb, prefix, indent, tp.getCause());
036            prefix = null; // to avoid adding it more than once
037        }
038        ThrowableProxyUtil.indent(sb, indent - 1);
039        if (prefix != null) {
040            sb.append(prefix);
041        }
042        ThrowableProxyUtil.subjoinFirstLineRootCauseFirst(sb, tp);
043        sb.append(CoreConstants.LINE_SEPARATOR);
044        subjoinSTEPArray(sb, indent, tp);
045        IThrowableProxy[] suppressed = tp.getSuppressed();
046        if (suppressed != null) {
047            for (IThrowableProxy current : suppressed) {
048                recursiveAppendRootCauseFirst(sb, CoreConstants.SUPPRESSED,
049                        indent + ThrowableProxyUtil.SUPPRESSED_EXCEPTION_INDENT, current);
050            }
051        }
052    }
053}