使用p6spy监视mybatis输出sql

由于工程是maven创建的,在pom.xml里添加


<!-- p6spy自动打印完整sql -->
<dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>2.1.3</version>
        </dependency>


并在src/main/resource下添加spy.properties,并添加


driverlist=com.mysql.jdbc.Driver

appender=cn.com.mofit.edocSafe.util.MyP6SpyLogger


编写自定义的Logger

内容如下:


package cn.com.mofit.edocSafe.util;




import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;


import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import com.p6spy.engine.spy.appender.StdoutLogger;


public class MyP6SpyLogger
  extends StdoutLogger
{
  private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
  
  public  void setLogfile(String fileName)
  {
    try
    {
      this.qlog = new PrintStream(new FileOutputStream(fileName, true));
    }
    catch (IOException e)
    {
      e.printStackTrace(System.err);
    }
  }
  
  public void logSQL(int connectionId, String now, long elapsed, String category, String prepared, String sql)
  {
    String judgeSql = sql.trim().toLowerCase();
    if ((judgeSql.startsWith("select")) || (judgeSql.startsWith("insert")) || (judgeSql.startsWith("update")) || (judgeSql.startsWith("delete")))
    {
      String logEntry = "----------# " + this.format.format(Long.valueOf(System.currentTimeMillis())) + " | took " + elapsed + "ms | " + category + " | connection " + connectionId + "\n" + sql + "; \n";
      
      logText(logEntry);
    }
  }
  public void logText(String text) {
 super.setStrategy(new MessageFormattingStrategy() {

@Override
public String formatMessage(int connectionId, String now, long elapsed,
String category, String prepared, String sql) {
String judgeSql = sql.trim().toLowerCase();
   if ((judgeSql.startsWith("select")) || (judgeSql.startsWith("insert")) || (judgeSql.startsWith("update")) || (judgeSql.startsWith("delete")))
   {
     String logEntry = "----------# " + MyP6SpyLogger.format.format(Long.valueOf(System.currentTimeMillis())) + " | took " + elapsed + "ms | " + category + " | connection " + connectionId + "\n" + sql + "; \n";
     
     return logEntry;
   }
   return null;
}
});
 super.logText(text);
  }
}


然后编译工程,重新部署,重启即可

你可能感兴趣的:(mybatis)