开发者

Writing Output & Error to Log files using PumpStreamHandler

开发者 https://www.devze.com 2023-02-20 19:31 出处:网络
I have been searching for a while to get a good example for writing Process output & error stream to log file.

I have been searching for a while to get a good example for writing Process output & error stream to log file. I use apache-commons exec library to execute my process. Following a code sample to demonstrate that

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


Following is the code to achieve this.

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

This is how we can use the above class.

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

Using apache-commons exec like this makes code & life (of a programmer) so simple. I was able to discard a huge amount of code that used Runtime.exec to execute commandline commands.

0

精彩评论

暂无评论...
验证码 换一张
取 消