8

我一直在寻找一个很好的例子来将进程输出和错误流写入日志文件。我使用 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);
}
4

1 回答 1

17

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

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);
    }
}

这就是我们可以使用上述类的方式。

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);
}

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

于 2011-03-31T11:28:44.647 回答