I have a Java Webapplication running on Tomcat, executing Shell scripts at runtime in which many "echo" commands are executed.
My problem is that I'd like all my logs to appear in a log4j RollingFileAppender, ie:
- Java Log4j logs (which is easy to do)
- Shell echo commands logs as well (which is the tricky part to me)
The Shell scripts are run via java.lang.Process class. So far, I've managed to output the inputStream and errorStream of the process to System.out thanks to the log4j-provided StreamUtils.copy() method.
But then this is fine to get some ConsoleAppender output, but not a RollingFileAppender output.
Is there any convenient way to redirect the Process streams to a RollingFileAppender? In Log4j configuration or from the Java code?
Here is my LOG4J appender conf:
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<param name="Threshold" value="DEBUG" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} [%-20.20t] %-5p [%-25.25c{1}] - %m%n" />
</layout>
</appender>
<appender name="FILE" class="org.apache.log4j.RollingFileAppender">
<param name="Threshold" value="DEBUG" />
<param name="File" value="&LOG_DIR;/&PROJECT_NAME;.log" />
<param name="Append" value="&APPEND;" />
<param name="MaxFileSize" value="&MAX_SIZE;" />
<param name="MaxBackupIndex" value="&MAX_BACKUP;" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} | %-21.21X{applicationId}| %-40.40t| %-5p |%-25.25c{1}| - %m%n" />
</layout>
</appender>
Here is my launching script code:
ProcessBuilder pb = new ProcessBuilder("sh", "script.sh");
Process p = pb.start();
StreamUtils.copy(p.getInputStream(), System.out);
StreamUtils.copy(p.getErrorStream(), System.out);
int result = p.waitFor();
LOG.info("Script ended with result " + result);
return (result == 0);