I am implementing Custom logging in Jetty11 and getting the null pointer exception for the below code while fetching anything from the request object. I know the reason but do not the solution to it. The reason is: calling the request object methods before setting it. I know, there should be another way to do it. My use case is to set the int and string attributes to the logger. In this example, I am calling request.getMethod() but I also have to call other methods as well
import org.eclipse.jetty.server.CustomRequestLog;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
public class JettyCustomLogger extends CustomRequestLog
{
private static Request request;
@Override
public void log(Request request, Response response)
{
this.request = request;
super.log(request, response);
}
public JettyCustomLogger(Writer writer, String logStr)
{
super(writer, setCustomAttributesToLog(logStr));
}
private static String setCustomAttributesToLog(String logStr)
{
String method = request.getMethod();
StringBuilder logBuffer = new StringBuilder(logStr);
logBuffer.append(method);
logBuffer.append("Ashish");
logBuffer.append(" ");
logBuffer.append("Goyanka");
logBuffer.append(" ");
logBuffer.append("absgdh");
logBuffer.append(" ");
return logBuffer.toString();
}
}
Note: this code works fine if I don't call request object methods.
Update: the reason to create setCustomAttributesToLog() is that I need to fetch the string parameters from other methods on runtime but here, I have given hardcoded string for code readability