title: Removing access to System.out in java
body: <p>I maintain an application which acts as a container for multiple individual programs. These programs have their own dedicated logging facility, i.e. everything they log does to a special log file.</p>
  
  <p>Nevertheless, application developers seem to <em>love</em> to throw <code>System.out.println</code> and <code>e.printStackTrace</code> calls all over, making it impossible to maintain a clean console when running the container.</p>
  
  <p>How can I prevent these applications from polluting <code>System.out</code> and <code>System.err</code>?</p>
  
  <hr>
  
  <p>Implementation notes:</p>
  
  <ul>
  <li>the applications use Log4j for logging;</li>
  <li>the container also uses the console for logging, but it is strictly reserved for lifecycle events and problems, so I still need the console;</li>
  <li>the applications are loaded using a custom classloader, but no security checks are applied.</li>
  </ul>
  
  <hr>
  
  <p><em>Update</em>:</p>
  
  <p>Simply redirecting <code>System.out</code> would not work since it redirects all output, so something like this fails:</p>
  
  <pre><code>    System.setOut(new PrintStream(new OutputStream() {
  
          @Override
          public void write(int b) {
  
              throw new Error("Not on my watch you don't");
  
          }
      }));
  
      Logger logger = Logger.getLogger(Runner.class);
      logger.info("My log message");
  </code></pre>
  
  <p>This should succeed.</p>
  
  <p><em>Update 2:</em></p>
  
  <p>The applications are loaded and configured using code similar to</p>
  
  <pre><code>App app = new UrlClassLoader(...).loadClass(className)).newInstance();
  app.setLogger(loggerForClass(app));
  </code></pre>
  
  <p>Log4j is loaded from the system class loader.</p>