【问题标题】:Can Jetty capture System.out and System.err to a log file?Jetty 可以将 System.out 和 System.err 捕获到日志文件中吗?
【发布时间】:2017-06-23 15:47:35
【问题描述】:
我正在使用 Jetty 嵌入式服务器,从一个遗留 jar 构建一个 REST api,它对 println 有很多非常有用的调用(我运行它的类并在控制台中打印东西)。我现在正尝试将这些 println 连同请求状态一起保存在一个文件中,但 NCSARequestLog 只记录文件日期和响应代码。那么有没有办法将所有内容记录在文件中?我很确定这是可能的,因为在我们将遗留 jar 包装在部署到 Glassfish 中的 war 文件中之前,所有打印结果都会显示在服务器日志中。
谢谢
【问题讨论】:
标签:
java
logging
jetty
embedded-jetty
【解决方案1】:
在jetty-util-<ver>.jar 中有一个名为RolloverFileOutputStream 的类,可以对其进行实例化,然后设置为接管System.out 和System.err 的滚动
一个例子:
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");
}
}