com.p6spy.engine.spy.appender.HibernateFormat Maven / Gradle / Ivy
package com.p6spy.engine.spy.appender;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* @see com.p6spy.engine.common.P6Util#singleLine(String)
* @see com.p6spy.engine.spy.appender.MultiLineFormat
*/
public class HibernateFormat implements MessageFormattingStrategy {
private final boolean hibernate = ClassUtils.isPresent("org.hibernate.engine.jdbc.internal.Formatter", getClass().getClassLoader());
@Override
public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('#');
stringBuilder.append(now);
stringBuilder.append(" | took ");
stringBuilder.append(elapsed);
stringBuilder.append("ms | ");
stringBuilder.append(category);
stringBuilder.append(" | connection ");
stringBuilder.append(connectionId);
if (StringUtils.hasText(prepared)) {
stringBuilder.append('|');
stringBuilder.append(prepared);
if (!StringUtils.hasText(sql)) {
sql = prepared;
}
if (this.hibernate) {
sql = getFormatter(prepared.charAt(0)).format(sql);
}
stringBuilder.append("|");
stringBuilder.append(sql);
}
return new String(stringBuilder);
}
private org.hibernate.engine.jdbc.internal.Formatter getFormatter(char ch) {
ch = Character.toUpperCase(ch);
boolean dml = (ch == 'S' || ch == 'I' || ch == 'U' || ch == 'D');
return dml ? org.hibernate.engine.jdbc.internal.FormatStyle.BASIC.getFormatter() : org.hibernate.engine.jdbc.internal.FormatStyle.DDL.getFormatter();
}
}