user4052054
user4052054

Reputation: 378

Can Jetty capture System.out and System.err to a log file?

I am working with Jetty embedded server, building a REST api out of a legacy jar, which has a lot of critically useful calls to println (I run its classes and it prints stuff in console). I am trying now to have these printlns in a file, along with the requests status, but the NCSARequestLog only logs in the file date and code of the responses. Is there a way to log everything in a file then? I'm pretty sure it is possible because before we were wrapping the legacy jar in a war file deployed into Glassfish, and all prints used to show up in the server log.

Thanks

Upvotes: 0

Views: 829

Answers (1)

Joakim Erdfelt
Joakim Erdfelt

Reputation: 49487

In the jetty-util-<ver>.jar there is a class called RolloverFileOutputStream which can be instantiated and then set to take over the roll of System.out and System.err

An example of this:

package demo;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.TimeZone;

import org.eclipse.jetty.util.RolloverFileOutputStream;

public class ConsoleCaptureDemo
{
    public static void main(String[] args) throws IOException
    {
        File loggingDir = new File("logs");
        if (!loggingDir.exists())
        {
            if (!loggingDir.mkdirs())
            {
                throw new RuntimeException("Unable to create directory: " + loggingDir);
            }
        }

        String loggingFile = new File(loggingDir, "yyyy_mm_dd.jetty.log").getAbsolutePath();
        boolean append = false;
        int retainDays = 90;
        TimeZone zone = TimeZone.getTimeZone("GMT");
        RolloverFileOutputStream logStream = new RolloverFileOutputStream(loggingFile, 
             append, retainDays, zone);
        System.out.println("Look at " + logStream.getFilename());
        PrintStream logWriter = new PrintStream(logStream);

        System.setOut(logWriter);
        System.setErr(logWriter);

        System.out.println("From System.out - hi there");
        System.err.println("From System.err - hello again");
    }
}

Upvotes: 1

Related Questions