我一直在寻找一个很好的例子来编写Process output&错误流到日志文件。 我使用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);
}
答案 0 :(得分: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);
}
}
这就是我们如何使用上述类。
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执行命令行命令的代码。