package cn.com.qtgl.config; import cn.hutool.log.Log; import com.alibaba.druid.filter.FilterAdapter; import com.alibaba.druid.filter.FilterChain; import com.alibaba.druid.proxy.jdbc.StatementProxy; import com.alibaba.druid.sql.SQLUtils; import com.mysql.jdbc.PreparedStatement; import java.sql.SQLException; /** * @author * @version 1.0 * @date 2019/12/3 16:34 * 打印可执行sql语句 */ public class SqlLogFilter extends FilterAdapter { private static final Log log = Log.get(); private static final SQLUtils.FormatOption FORMAT_OPTION = new SQLUtils.FormatOption(false, false); @Override public void statement_close(FilterChain chain, StatementProxy statement) throws SQLException { if (log.isDebugEnabled()) { if (statement.getRawObject() instanceof PreparedStatement) { PreparedStatement preparedStatement = (PreparedStatement) statement.getRawObject(); String sql = preparedStatement.asSql(); //定制sql输出格式,可以去掉 sql = SQLUtils.formatMySql(sql, FORMAT_OPTION); log.debug("sql:{}", sql); } } super.statement_close(chain, statement); } }
如果使用8.x的mysql 驱动 可以使用ClientPreparedStatement这个类
以上配置仅试用mysql,如果要支持其他数据可以使用通用配置支持所有数据库
Slf4jLogFilter LOG_FILTER = new Slf4jLogFilter(); LOG_FILTER.setStatementExecutableSqlLogEnable(true); LOG_FILTER.setResultSetLogEnabled(false); LOG_FILTER.setConnectionLogEnabled(false); LOG_FILTER.setDataSourceLogEnabled(false); LOG_FILTER.setStatementCreateAfterLogEnabled(false); LOG_FILTER.setStatementPrepareAfterLogEnabled(false); LOG_FILTER.setStatementPrepareCallAfterLogEnabled(false); LOG_FILTER.setStatementExecuteAfterLogEnabled(false); LOG_FILTER.setStatementExecuteQueryAfterLogEnabled(false); //不进行格式化 LOG_FILTER.setStatementSqlFormatOption(new SQLUtils.FormatOption(false, false)); LOG_FILTER.setStatementExecuteUpdateAfterLogEnabled(false); LOG_FILTER.setStatementExecuteBatchAfterLogEnabled(false); LOG_FILTER.setStatementCloseAfterLogEnabled(false); LOG_FILTER.setStatementParameterSetLogEnabled(false); LOG_FILTER.setStatementParameterClearLogEnable(false); LOG_FILTER.setStatementLogErrorEnabled(false);