In a larger program, I am using a static java.util.logging.Logger
instance, but redirecting System.err
to several different files in succession. The Logger
fails to log the second time I try to redirect System.err
.
Here's a test program to show the problem:
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.logging.Logger;
class TestRedirect {
static final Logger logger = Logger.getLogger("test");
public static void main(String[] args) throws FileNotFoundException {
for (int i = 1; i <= 2; i++) {
TestRedirect ti = new TestRedirect();
ti.test(i);
}
}
void test(int i) throws FileNotFoundException {
PrintStream filePrintStream = new PrintStream("test" + i + ".log");
PrintStream stderr = System.err; // Save stderr stream.
System.setErr(filePrintStream); // Redirect stderr to file.
System.err.println("about to log " + i);
logger.info("at step " + i);
System.setErr(stderr); // Restore stderr stream.
filePrintStream.close();
}
}
Here's the output:
test1.log:
about to log 1
Jan 28, 2014 4:34:20 PM TestRedirect test
INFO: at step 1
test2.log:
about to log 2
I thought I would see a Logger
-generated message in test2.log as well. Why does the Logger
stop working, and what could I do about this?