Search code examples
javaloggingstderrjava.util.logging

System.setErr() doesn't restore console logging after stderr closed


My app uses System.setErr() to change stderr to a stream which will eventually be closed. Immediately after it's closed I immediately use System.setErr() again to change stderr to a working stream, which goes fine for when my code does something like System.err.println(), but logging with java.util.logging to the console (that is, to stderr) no longer works.


Solution

  • To solve this, I had to re-read the logging configuration file and then put back in the console logging handler myself:

    import java.util.logging.ConsoleHandler;
    import java.util.logging.Loggger;
    import java.util.logging.LogManager;
    
    ...
    
    System.setErr(otherStream);
    
    try {
        LogManager.getLogManager().readConfiguration();
    }
    catch(java.io.IOException e) {
        // ...
    }
    
    Logger.getGlobal().addHandler(new ConsoleHandler());