【问题标题】:In Java, how can I redirect System.err for a specific method invocation?在 Java 中,如何为特定方法调用重定向 System.err?
【发布时间】:2020-05-21 14:57:54
【问题描述】:

假设我在 Java 中有一些方法 method(),它调用与堆栈跟踪结构相对应的一系列方法。可能是这些“子方法”之一调用打印到 System.err / stderr。有没有办法阻止与该方法相关的所有打印?我找到了this page,它解释了如何通过完全临时重定向 System.err 来做到这一点,但我担心这可能会导致其他错误(我确实想要跟踪)不会出现在控制台中。

【问题讨论】:

  • 简答:否。加长答案:是。暂时完全重定向System.err。是的。它可能导致其他错误。我看到的唯一其他选择是删除method() 中的所有 println 调用。或者,更好的是,使用实际的记录器而不是将所有内容都写入PrintStream(s)。
  • @Elliot:我的问题是“method()”调用了我无法控制的库中的方法。 /
  • 一个自定义流,试图过滤掉不应该打印的东西和应该打印的东西。 JVM 无法知道您认为重要的信息和不重要的信息,它只有一个 System.err
  • 问题是System.errglobal 并且任何同时运行的东西也会被重定向。反汇编库并手动更改其操作可能会更好。或者请图书馆的主人来做。

标签: java console stdout stderr


【解决方案1】:

您可以尝试在方法调用之前存储原始的 PrintStream 和 Override,并在调用后恢复它

 public static void main(String[] args) {
        // Before methods' invocation
        final PrintStream orgErr = System.err;

        System.setErr(new PrintStream(new OutputStream() {

            @Override
            public void write(int b) throws IOException {

            }
        }));

        callMethod();

        // After methods' invocation
        System.setErr(orgErr);
    }

    static void callMethod() {
        try {
            throw new RuntimeException("failed");
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

【讨论】:

    【解决方案2】:

    除非您正在运行多个线程,否则使用您链接到的帖子中的方法应该可以工作(除了 System.setErr 而不是 System.setOut

    public void method(){
        //This submethod will print errors
        submethod1();
    
        PrintStream original = System.err;
        System.setErr(new PrintStream(new OutputStream(){
            public void write(int i){ }
        }));
    
        //This submethod will NOT print errors
        submethod2();
    
        System.setErr(original);
    
        //This submethod will print errors
        submethod3();
    }
    

    只要您在调用任何您确实希望从中出错的子方法之前恢复原始状态,就可以了

    【讨论】:

      猜你喜欢
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多