Shane
Shane

Reputation: 313

Log4J: Redirect Stderr message to the main log file

I have a cmd line tool we are deploying to the customer soon. I have a nasty StdErr message in appearing in the cmd window from a framework I'm consuming and I'm struggling to redirect that message to my log file with Log4J.

Here is my log4j.xml file:

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration debug="false" xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="file" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false" />
        <param name="maxFileSize" value="500MB" />
        <param name="maxBackupIndex" value="5" />
        <param name="file" value="test.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
        </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="file" />
    </root>

</log4j:configuration>

I have googled around and I cant find anyone with a similar case to me.

I have redirected it using the following lines but I'd rather redirect it with log4j so everything is in the same file

File file = new File("error.log");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setErr(ps);

I cant redirect it with JBoss or tomcat settings because I'm not using a container. It is a JAR directly on the CMD line.

Note: I want STDOUT to still go to the CMD window as that is the menu system for the user.

Upvotes: 3

Views: 8118

Answers (1)

Shane
Shane

Reputation: 313

I found this question here, the accepted answer is the one I needed: log4j redirect stdout to DailyRollingFileAppender

Turns out I was trying to figure out a way to fix it in XML config when in reality I should have been trying to fix in in code by redirecting stdErr with System.setErr().

Upvotes: 3

Related Questions