使用PumpStreamHandler将输出和错误写入日志文件

Sal*_*gzi 8 java runtime exec apache-commons apache-commons-exec

我一直在寻找一个很好的例子,用于将Process输出和错误流写入日志文件.我使用apache-commons exec库来执行我的进程.下面的代码示例来演示

public static int executeCommand(CommandLine command, Logger log) throws ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);

    PumpStreamHandler psh = new PumpStreamHandler();
    executor.setStreamHandler(psh);

    return executor.execute(command);
}
Run Code Online (Sandbox Code Playgroud)

Sal*_*gzi 16

以下是实现此目的的代码.

class ExecLogHandler extends LogOutputStream {
    private Logger log;

    public ExecLogHandler(Logger log, Level logLevel) {
        super(logLevel.toInt());
        this.log = log;
    }

    @Override
    protected void processLine(String line, int logLevel) {
        log.log(Level.toLevel(logLevel), line);
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我们如何使用上面的类.

public static int executeCommand(CommandLine command, Logger log) throws ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);

    PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(log, Level.DEBUG), new ExecLogHandler(log, Level.ERROR));
    executor.setStreamHandler(psh);

    return executor.execute(command);
}
Run Code Online (Sandbox Code Playgroud)

使用像这样的apache-commons exec可以使代码和生活(程序员)变得如此简单.我能够丢弃大量使用Runtime.exec执行命令行命令的代码.