在system.out.println的代码中查找位置



假设我正在一个非常大的项目中工作,并且注意到有一个空的打印行,所以我假设有一个System.out.println(");位于代码中的某个位置。除了在整个项目中搜索所有出现的System.out.println之外,我该如何尝试弄清楚它在哪里?

如果您使用的是Java 8+,Durian有一个StackDumper类,它可以很容易地找到打印给定行的位置:

StackDumper.dumpWhenSysOutContains("SomeTrigger")

当打印"SomeTrigger"时,它将被转储到System.err:

+----------
| Triggered by SomeTrigger
| at package.MyClass.myMethod(MyClass.java:62)
| (the rest of the stacktrace)
+----------/

对于您的情况(查找空字符串),它有点复杂:

PrintStream sysOutClean = System.out;
StringPrinter sysOutReplacement = new StringPrinter(StringPrinter.stringsToLines(line -> {
    if (line.isEmpty()) {
        StackDumper.dump("Found empty line");
    }
    sysOutClean.println(line);
}));
System.setOut(sysOutReplacement.toPrintStream());

现在,如果有这样的东西:

System.out.println("ABC");
System.out.println("123");
System.out.println("");
System.out.println("DEF");

然后你的控制台会像这样:

ABC
123
+----------
| Found empty line
| at package.MyClass.myMethod(MyClass.java:62)
| (the rest of the stacktrace)
+----------/
DEF

您可以实现自己的PrintStream,并使用System.setOut来替换默认的stdout。然后在类中放置调试标记(如果打印了空字符串),或者通过调用堆栈打印出方法名称(抛出并捕获异常并获取堆栈信息)。

示例:

/** Control sysout prints */
public static void main(String[] arg) throws Exception {
     System.out.println("Default"); //print normally
     SysOutController.setSysOutLocationAddressor();
     System.out.println("With Address"); //prints with calling location, and on click location cursor directly focus when System.out.**() called
     SysOutController.ignoreSysout();
     System.out.println("Ignored"); //this line will never prints
     SysOutController.resetSysOut();
     System.out.println("Default"); //print normally as it is (reset)
}

只需调用以下类的方法,即可帮助开发人员控制sysout

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
/** 
 * Class which controls System.out prints in console <br/>
 * this class will helps developers to control prints in console
 * @implSpec
 * <pre><code>
 * System.out.println("Default"); //print normally
 * 
 * SysOutController.setSysOutLocationAddressor();
 * System.out.println("With Address"); //prints with calling location
 * 
 * SysOutController.ignoreSysout();
 * System.out.println("Ignored"); //this line will never prints
 * 
 * SysOutController.resetSysOut();
 * System.out.println("Default"); //print normally as it is (reset)
 * </code></pre>
 * @author Dharmendrasinh Chudasama
 */
public class SysOutController {
    private static void setOut(OutputStream out){
        System.setOut(new PrintStream(out));
    }
    private static final OutputStream CONSOLE = new FileOutputStream(FileDescriptor.out);
    /**
     * Reset System.out.print* method
     * @author Dharmendrasinh Chudasama
     */
    public static void resetSysOut() { setOut(CONSOLE); }
    /**
     * System.out.print* will not print anything in console
     * @author Dharmendrasinh Chudasama
     */
    public static void ignoreSysout() {
        setOut(new OutputStream() {
            @Override public void write(int b) throws IOException {}
        });
    }
    /**
     * Address/location of calling System.out.* method will append in console
     * @author Dharmendrasinh Chudasama
     */
    public static void setSysOutLocationAddressor() {
        setOut(new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                if(b=='n'){ //if newLine
                    final StackTraceElement callerStEl = new Throwable().getStackTrace()[9];
                    String pathData =
                        "u001B[37m"    //low-visibality
                        + "t :: ("+callerStEl.getFileName()+":"+callerStEl.getLineNumber()+") ["+callerStEl+"]"  //code path
                        + "u001B[0m ";  //reset
                    CONSOLE.write(pathData.getBytes());
                }
                CONSOLE.write(b);
            }
        });
    }
}

这也可能是由于库的某些原因,如果你觉得这只是因为System.out.println,那么

解决方案1:下面的代码片段应该可以帮助您找到执行它的位置。

        import java.io.FileNotFoundException;
        import java.io.PrintStream;
        public class CustomPrintStream extends PrintStream {
        public CustomPrintStream(String fileName) throws FileNotFoundException {
            super(fileName);
        }
            @Override
            public void print(String s) {
                try{
                    if(s == null || s.equals("")){
                        throw new Exception("Invalid print message");
                    }
                    super.print(s);
                }catch(Exception e){
                    //TODO Change to your logger framework and leave it as same 
                    e.printStackTrace();
                }
            }
            public static void main(String[] args) {
                try {
 //TODO : Change to your favorite path and make sure mentioned
//file is available
                    CustomPrintStream customPrintStream = new CustomPrintStream
    ("/home/prem/Desktop/test.log");
                    System.setOut(customPrintStream);
                    System.out.println("");
                } catch (FileNotFoundException e) {
                    //TODO Change to your logger framework and leave it as same 
                    e.printStackTrace();
                }
            }
        }

解决方案2:由于IDE是可用的,请从他们那里获得帮助。如果您正在使用eclipse菜单->搜索->文件搜索->放置系统.out.println(");在包含搜索和搜索它。

我宁愿说不要在任何代码中使用System.out.println,因为您可以使用checkstyle,并确信因此没有开发人员使用它们。

定义一个类NewPrintStream扩展PrintStream

import java.io.FileNotFoundException;
import java.io.PrintStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NewPrintStream extends PrintStream {
  private static final Logger LOGGER = LoggerFactory.getLogger(NewPrintStream.class);
  public NewPrintStream(String fileName) throws FileNotFoundException {
    super(fileName);
  }
  @Override
  public void println(String x) {
    LOGGER.info("xxxxxxx", new Exception("xxxx"));
  }
}

然后在主类中设置stdout/stderr打印流

System.setOut(new NewPrintStream("aaa"));
System.setErr(new NewPrintStream("aaa"));

PrintStream.println(String x)中放置一个条件断点,条件设置为x.equals("")或任何字符串。

相关内容

  • 没有找到相关文章

最新更新