在Jetty 10中使用自定义日志记录时,自定义属性在新行中记录



我正在Jetty10中实现自定义日志记录,以便在请求中添加自定义属性,并且我能够使用下面的代码来完成它。我已经硬编码userId, username, lastName等参数的可读性,但它将在运行时获取。

package net.codejava.javaee;
import java.io.IOException;
import org.eclipse.jetty.server.CustomRequestLog;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
public class MyJettyLogger extends CustomRequestLog
{
private Request request;
@Override
public void log(Request request, Response response)
{
this.request = request;
request.getMethod();
Writer writerObj = getWriter();
String logString = setCustomAttributesToLog();
super.log(request, response);
try {
writerObj.write(logString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public MyJettyLogger(Writer writer, String logStr)
{
super(writer, logStr);
}
private String setCustomAttributesToLog(){
StringBuilder logBuffer = new StringBuilder("");

String userId="1234";
String username = "Ashish";
String lastName ="Goyanka";
String uri = request.getRequestURI();
String requestMethod = request.getMethod();

logBuffer.append(" ");
logBuffer.append(userId);
logBuffer.append(" ");
logBuffer.append(username);
logBuffer.append(" ");
logBuffer.append(lastName);
logBuffer.append(" ");
logBuffer.append(uri);
logBuffer.append(" ");
logBuffer.append(requestMethod);
return logBuffer.toString() ;
}
}

但问题是他们在新行中打印日志,如下

[0:0:0:0:0:0:0:1]——[31日/8月/2021:11:53:25 + 0000]"HTTP/1.1/MyFirstServlet444/index . jsp来"200481 "-"Mozilla/5.0(Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML,如Gecko)Chrome/92.0.4515.159 Safari 537.36">

1234 Ashish Goyanka/MyFirstServlet444/index.jsp GET

我只是希望它们在请求后打印在同一行。我们有什么办法吗?

您首先调用下面的代码,这将很好地格式化请求/响应并将其作为新行记录。

super.log(request, response);

public void log (Request Request, Response Response)

将请求和响应信息写入输出流。

log
public void log​(Request request, Response response)
Writes the request and response information to the output stream.
Specified by:
log in interface RequestLog
Parameters:
request - The request to log.
response - The response to log. Note that for some requests the response instance may not have been fully populated (Eg 400 bad

请求响应不发送servlet响应对象)。因此有关日志的基本信息,最好查阅Response.getCommittedMetaData()和Response.getHttpChannel()直接。参见:RequestLog.log(请求、响应)


如果你不想有一个新的行,然后删除super.log()

并自定义打印:

writerObj.write("logStringThatHasRequestAndResponseInformation here");

最新更新