java log4j 2 System.out.println关闭

时间:2017-02-20 11:00:39

标签: java console log4j2

在我的代码中:

System.out.println("hello println");
mylogger.info("hello info");
mylogger.debug("hello debug");

我只想在我的控制台中记录logger(无打印" hello println"通过System.out.println):

你好信息

你好调试

我的log4j文件是:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="consoleInfo" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss}]: %m%n" />
        </layout>
    </appender>

    <category name="org.openqa.selenium">
        <priority value="off" />
    </category>
    <category name="org.apache.log4j">
        <priority value="off" />
    </category>

    <root>
        <level value="INFO" />
        <appender-ref ref="consoleInfo" />
    </root>

</log4j:configuration>

2 个答案:

答案 0 :(得分:0)

你可以&#34;关闭&#34; System.out将其替换为只忽略所有输入的编写器:

System.out.println("This is written.");

System.setOut(new PrintStream(new OutputStream() {
    @Override
    public void write(int b) throws IOException {}
}));

System.out.println("Not written!");

如果你碰巧在类路径上有Guava,它可以缩短为

System.setOut(new PrintStream(ByteStreams.nullOutputStream()));

答案 1 :(得分:0)

您可以通过将系统的out参数指向appender,将系统输出重定向到appender,如下所示:

SELECT @row_num1 := @row_num1 + 1 AS RIdx2
     , C.color
  FROM colors C
  CROSS
  JOIN (SELECT @row_num1:=0) vars 
 ORDER 
  BY color;

这样,您的所有系统输出和错误都将到达日志文件。