Tuesday 22 December 2015

Restrict Logging of StackTrace in Java


Problem :
we have a requirement of restricting the logging of full stacktrace due to many reasons.

Solution:
we have two ways to control this printing of stakctrace.
one solution fits for application which is in devlopement stage and second one is for production stage.

1. Application in DEV STAGE :
so we have option to customize the printing of stack trace.
please go through this method .

public String customizeStackTrace(Throwable e, int maxLines)
    {
       
        StringBuilder newStackStrace = new StringBuilder(e.getMessage()+"\n"); 
        StackTraceElement[] elements = e.getStackTrace();
        for (int i = 0; i < maxLines; i++)
        {
            newStackStrace.append(elements[i]).append("\n");
        }
        return newStackStrace.toString();
    }



2. Application in PROD STAGE:
 so we have to control using log4j .
If you are using log4j version lessthan 1.12.16 then you need to upgrade to 1.2.16 or more.
and use layout as
<layout class="org.apache.log4j.EnhancedPatternLayout">
            <param name="ConversionPattern" value=" %d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1}: %m%n %throwable{10}" />
        </layout>




I think you found right information here. see you soon with new issue i found..