如何找到打印所在的位置?

Ive*_*ves 1 java printing debugging

我正在使用IntelliJ开发一个旧的java应用程序项目,源代码非常庞大.一类有一种方法,可以在播放时每帧打印视频信息.我想禁用此代码进行打印,但我不知道它来自何处或类名是什么.当我直接搜索字符串时它没有显示出来.是否有更聪明的方法来找到打印所在的位置?

(来自评论):

输出线是 [isDeveloper true]------ get duration(=3.552653) is test impl ------

AJN*_*eld 5

替换System.out为您自己的PrintStream,使用System.setOut()它,使它与(un)所需的输出匹配,在match子句上放置一个断点,并查看堆栈跟踪.


由于PrintStream有许多方法,而不是覆盖生成(非)所需输出时可能调用的所有可能方法,让我们将所有PrintStream输出指向FilterOutputStream我们自己的设计; 那么我们只需要覆盖一个方法,但我们需要重建我们的字符串.

例:

class Prospector extends FilterOutputStream {

    int count = 0;

    private OutputStream original;

    public Prospector(OutputStream out) {
        super(out);
        original = out;
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        String buffer = new String(b, off, len, StandardCharsets.ISO_8859_1);
        if (buffer.contains("]------ get duration(=")) {
            if (count == 0) {
                new Exception().printStackTrace(original);
            }
            count++;  // Set breakpoint here
        }
        super.write(b, off, len);
    }
}
Run Code Online (Sandbox Code Playgroud)

程序启动时,安装一个新的PrintStream包装原件在我们的Prospector:

System.setOut(new PrintStream(new Prospector(System.out)));
Run Code Online (Sandbox Code Playgroud)

在指示的行上设置断点.当程序在断点处停止时,查找堆栈跟踪以查找生成输出的类/方法.

当神秘课产生你的目标线时,可能就像......

System.out.format("[%s %s]------ get duration(=%f) is %s -------%n",
    "isDeveloper", "true", 3.552653, "test impl");
Run Code Online (Sandbox Code Playgroud)

...此方法可以被多次调用,并且buffer连续包含该行的各个部分.在上面的例子中,这将是:

  • "["
  • "isDeveloper"
  • " "
  • "true"
  • "]------ get duration(="
  • "3.552653"
  • ") is "
  • "test impl"
  • " -------"
  • "\n"

理想情况下,]------ get duration(=应该足够独特,以找到您正在寻找的类/方法,但您可以根据需要进行调整.

整个文本也可以格式化为单个文本String,并在一次调用中打印出来.这就是为什么.contains(...)用于匹配所需的输出.