仅显示有效的SQL字符串P6Spy

use*_*r22 4 sql p6spy

我正在使用p6spy来记录我的程序生成的sql语句.输出的spy.log文件的格式如下所示:

current time|execution time|category|statement SQL String|effective SQL string
Run Code Online (Sandbox Code Playgroud)

我只是想知道是否有人知道是否有办法改变spy.properties文件并且只有最后一列,即有效的SQL字符串,输出到spy.log文件?我查看了属性文件,但没有找到任何似乎支持这个的东西.

谢谢!

Joh*_*erg 13

在spy.properties中有一个名为的属性logMessageFormat,您可以将其设置为自定义实现MessageFormattingStrategy.这适用于任何类型的记录器(即文件,slf4j等).

例如

logMessageFormat=my.custom.PrettySqlFormat
Run Code Online (Sandbox Code Playgroud)

使用Hibernate的漂亮的SQL格式化程序的一个例子:

package my.custom;

import org.hibernate.jdbc.util.BasicFormatterImpl;
import org.hibernate.jdbc.util.Formatter;

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

public class PrettySqlFormat implements MessageFormattingStrategy {

    private final Formatter formatter = new BasicFormatterImpl();

    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql) {
        return formatter.format(sql); 
    }

}
Run Code Online (Sandbox Code Playgroud)


Pet*_*vic 1

目前还没有提供这样的选项来仅通过配置来实现它。我认为你有两个选择

  • 填写新的错误/功能请求报告(这也可以为使用 p6spy 的其他人带来好处):https: //github.com/p6spy/p6spy/issues ? state=open 或
  • 提供自定义实现

对于后面的选项,我相信您可以通过自己的类来实现它(取决于您使用的记录器,我们假设您使用 Log4jLogger)。

好吧,如果你检查 Log4jLogger github以及sourceforge版本的相关部分,你的实现应该相当简单:

间谍属性:

appender=com.EffectiveSQLLog4jLogger
Run Code Online (Sandbox Code Playgroud)

实现本身可能如下所示:

package com;

import com.p6spy.engine.logging.appender.Log4jLogger;

public class EffectiveSQLLog4jLogger extends Log4jLogger {

  public void logText(String text) {
    super.logText(getEffectiveSQL(text));
  }

  private String getEffectiveSQL(String text) {
    if (null == text) {
      return null;
    }

    final int idx = text.lastIndexOf("|");

    // non-perfect detection of the exception logged case
    if (-1 == idx) {
      return text;
    }

    return text.substring(idx + 1); // not sure about + 1, but check and see :)
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,实现应覆盖 github(新项目主页,尚未发布版本)以及 sourceforge(原始项目主页,已发布 1.3 版本)。

请注意:我自己没有测试该提案,但这可能是一个很好的起点,并且从代码审查本身来看,我认为它是可行的。