001
014
015 package com.liferay.portal.kernel.log;
016
017 import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter;
018 import com.liferay.portal.kernel.util.UnsyncPrintWriterPool;
019 import com.liferay.portal.kernel.util.Validator;
020
021 import java.util.ArrayList;
022 import java.util.List;
023 import java.util.Properties;
024
025
028 public class LogUtil {
029
030 public static final boolean REMOVE_UNKNOWN_SOURCE = true;
031
032 public static final int STACK_TRACE_LENGTH = 20;
033
034 public static void debug(Log log, Properties props) {
035 if (log.isDebugEnabled()) {
036 UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter(
037 props.size() + 1);
038
039 props.list(UnsyncPrintWriterPool.borrow(unsyncStringWriter));
040
041 log.debug(unsyncStringWriter.toString());
042 }
043 }
044
045 public static void log(Log log, Throwable throwable) {
046 log(log, throwable, null);
047 }
048
049 public static void log(Log log, Throwable throwable, String message) {
050 if (throwable == null) {
051 if (Validator.isNotNull(message)) {
052 log.error(message);
053
054 return;
055 }
056
057 throw new IllegalArgumentException(
058 "Throwable or message must be set");
059 }
060
061 Throwable causeThrowable = throwable;
062
063 while (causeThrowable.getCause() != null) {
064 causeThrowable = causeThrowable.getCause();
065 }
066
067 StackTraceElement[] stackTraceElements = causeThrowable.getStackTrace();
068
069
070
071
072 if (stackTraceElements.length <= STACK_TRACE_LENGTH) {
073 if (Validator.isNotNull(message)) {
074 log.error(message, causeThrowable);
075 }
076 else {
077 log.error(causeThrowable);
078 }
079
080 return;
081 }
082
083 int count = 0;
084
085 List<StackTraceElement> stackTraceElementsList = new ArrayList<>();
086
087 for (StackTraceElement stackTraceElement : stackTraceElements) {
088
089
090
091
092
093 String className = stackTraceElement.getClassName();
094
095 boolean addElement = true;
096
097 if (REMOVE_UNKNOWN_SOURCE &&
098 (stackTraceElement.getLineNumber() < 0)) {
099
100 addElement = false;
101 }
102
103 if (className.startsWith("$") ||
104 className.startsWith("java.lang.reflect.") ||
105 className.startsWith("org.springframework.") ||
106 className.startsWith("sun.reflect.")) {
107
108 addElement = false;
109 }
110
111 if (addElement) {
112 stackTraceElementsList.add(stackTraceElement);
113
114 count++;
115 }
116
117 if (count >= STACK_TRACE_LENGTH) {
118 break;
119 }
120 }
121
122 stackTraceElements = stackTraceElementsList.toArray(
123 new StackTraceElement[stackTraceElementsList.size()]);
124
125 causeThrowable.setStackTrace(stackTraceElements);
126
127 if (Validator.isNotNull(message)) {
128 log.error(message, causeThrowable);
129 }
130 else {
131 log.error(causeThrowable);
132 }
133 }
134
135 }