io.hypersistence.utils.hibernate.query.QueryStackTraceLogger Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hypersistence-utils-hibernate-55 Show documentation
Show all versions of hypersistence-utils-hibernate-55 Show documentation
Utilities for Spring and Hibernate ORM 5.5 to 5.6
package io.hypersistence.utils.hibernate.query;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* The {@link QueryStackTraceLogger} allows you to log the stack trace that
* executed a given SQL query.
*
* @author Vlad Mihalcea
* @since 3.5.3
*/
public class QueryStackTraceLogger implements StatementInspector {
public static final String ORG_HIBERNATE ="org.hibernate";
public static String TAB = "\t";
public static String NEW_LINE = System.getProperty("line.separator");
private static final Logger LOGGER = LoggerFactory.getLogger(QueryStackTraceLogger.class);
private final String packageNamePrefix;
public QueryStackTraceLogger(String packageNamePrefix) {
this.packageNamePrefix = packageNamePrefix;
}
@Override
public String inspect(String sql) {
LOGGER.debug(
"This SQL query: [\n\t{}\n]\nwas generated by Hibernate like this: [\n{}\n]",
sql,
String.join(
NEW_LINE,
stackTraceElementsUpTo(packageNamePrefix)
.stream()
.map(e -> TAB + e.toString())
.collect(Collectors.toList())
)
);
return null;
}
/**
* Filter the stack trace based up to the provided package name prefix
*
* @param endPackageNamePrefix package name to match the {@link StackTraceElement}
* @return the {@link StackTraceElement} up to the matching the provided package name
*/
private List stackTraceElementsUpTo(String endPackageNamePrefix) {
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
List filteredStackTraceElements = new ArrayList<>();
boolean startPackageMatched = false;
boolean endPackageMatched = false;
for (StackTraceElement stackTraceElement : stackTraceElements) {
String className = stackTraceElement.getClassName();
if(!startPackageMatched) {
if(className.startsWith(ORG_HIBERNATE)) {
startPackageMatched = true;
} else {
continue;
}
}
if(!className.contains(endPackageNamePrefix)) {
if(!endPackageMatched) {
filteredStackTraceElements.add(stackTraceElement);
} else {
break;
}
} else if(!endPackageMatched) {
endPackageMatched = true;
filteredStackTraceElements.add(stackTraceElement);
}
}
return filteredStackTraceElements;
}
}