How to output logs from a Shell Script launched within Java in a log4j RollingFileAppender?

时光怂恿深爱的人放手 提交于 2019-12-05 13:24:54
mezzie

Are you using a thread? if so, you need to see https://stackoverflow.com/q/8229913/458901 to make it work with rolling appenders.

In conjunction with that, your thread can use this method that you can use to pass in a string array (your command with args if any) and will return you the output of that command. Of course, just use the string it returns to add to your log :)

private String execute(String[] command){
    //System.out.println(command);
    try{
        process = Runtime.getRuntime().exec(command);
        InputStream istream = process.getInputStream();
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        Reader reader = new BufferedReader(new InputStreamReader( istream ));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
        reader.close();
        istream.close();
        return writer.toString();
    }
    catch ( IOException e )
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "";
}

}

Here is the snippet of code I've used to log the output of my process. Pretty straightforward and seems to work. Thanks @mezzie.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

public class ProcessLoggerThread extends Thread {

private final static Logger LOGGER = Logger.getLogger(ProcessLoggerThread.class);

private InputStream inputStream;


public ProcessLoggerThread(InputStream inputStream) {
    super();

    this.inputStream = inputStream;
}


public void run() {
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = reader.readLine();
        while (line != null) {
            LOGGER.debug(line);
            line = reader.readLine();
        }
        reader.close();
        LOGGER.debug("End of logs");
    } catch (IOException e) {
        LOGGER.error("The log reader died unexpectedly.");
    }
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!