2011-03-31 68 views
8

我一直在尋找一段時間,以獲得一個很好的寫入日誌文件的過程輸出&錯誤流的示例。 我使用apache-commons exec庫來執行我的過程。以下代碼示例證明:使用PumpStreamHandler將輸出和錯誤寫入日誌文件

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

回答

14

以下是實現此目的的代碼。

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公地高管這樣使得代碼&壽命(程序員)那麼簡單。我能夠放棄使用Runtime.exec執行命令行命令的大量代碼。