将System.out.println重定向到日志

时间:2013-03-14 07:13:35

标签: java logging

在我的项目测试套件中有很多用途

System.out.println 

我正在尝试将这些输出重定向到日志文件(通过配置或单点而不重构整个项目),以便在必要时可以禁用以提高性能。我正在使用log4j进行日志记录。 有人知道这可能吗?如果是这样怎么办? 提前谢谢。

5 个答案:

答案 0 :(得分:4)

鉴于它最好取代D aac raw ADTS AAC (Advanced Audio Coding),有时我们别无选择。无论如何,我为此做了一点实用工具:

System.out.println()

然后,所有源自MyClass的println将被重定向到记录器。 See this post for more details...

SystemOutToSlf4j.enableForClass(MyClass.class)

答案 1 :(得分:2)

我的建议是尽可能重构。 有关可能的解决方案,请检查这些类似的问题

log4j redirect stdout to DailyRollingFileAppender

Redirect System.out.println to Log4J, while keeping class name information

答案 2 :(得分:2)

我认为您可以使用System.setOut(PrintStream)将输出设置为文件输出流。然后你可以将这一行放在BeforeClass方法中。我喜欢使用BaseTest类并将这行代码放在该类的beforeclass方法中。然后让所有测试用例扩展这个cclass。

答案 3 :(得分:1)

使用shell重定向。弄清楚" java"调用你的项目,如果你在大多数模糊的类UNIX系统上,ps aux | grep java会有所帮助。

然后使用>运行此命令/路径/到/日志文件。例如:

java -jar myjar.jar -cp path/to/lib.jar:path/to/otherlib.jar com.bigcorp.myproject.Main > /var/log/myproject.log

答案 4 :(得分:0)

public class RecursiveLogging {
public static void main(String[] args) {
    System.setOut(new PrintStream(new CustomOutputStream()));

    TestMyException.testPrint();
}

}

class CustomOutputStream extends OutputStream {
private Logger logger = Logger.getLogger(this.getClass());

@Override
public final void write(int b) throws IOException {
    // the correct way of doing this would be using a buffer
    // to store characters until a newline is encountered,
    // this implementation is for illustration only
    logger.info((char) b);
}

@Override
public void write(byte[] b, int off, int len) throws IOException {
    if (b == null) {
        throw new NullPointerException();
    } else if ((off < 0) || (off > b.length) || (len < 0) ||
               ((off + len) > b.length) || ((off + len) < 0)) {
        throw new IndexOutOfBoundsException();
    } else if (len == 0) {
        return;
    }
    byte[] pb = new byte[len];
    for (int i = 0 ; i < len ; i++) {
        pb[i] = (b[off + i]);
    }
    String str = new String(pb);
    logger.info(str);
}
}
相关问题