I need to get in logs the URI which triggered the [NOT FOUND 404] error. I use .getHeader(HttpHeaders.REFERER) and i'm getting null. The same i tried to use getRequestURL() and i'm getting the path of @RequestMapping method "/error".
For example: If a user enters: mywebsite.com/fdsfihdif and there is no such address, i should see this in logs like this [NOT FOUND 404] User [john@yahoo.com] tried to access this URI : [mywebsite.com/fdsfihdif]
Here is my errorControler:
@Controller
public class CustomErrorController implements ErrorController {
private static final Logger log = LogManager.getLogger(CustomErrorController.class);
@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (status != null) {
Integer statusCode = Integer.valueOf(status.toString());
if (statusCode == HttpStatus.NOT_FOUND.value()) {
//404 with the wrong URI entered by user
log.error("[NOT FOUND 404] User [" + auth.getName() + "] tried to access this URL : ["+ request.getRequestURL() +"] : [" + request.getHeader(HttpHeaders.REFERER) + "]";
return "errors/404";
} else {
//something else
return "errors/error";
}
}
return "error";
}
@Override
public String getErrorPath() {
return "/error";
}
}
Here is the output:
2018-06-22 18:48:59.507 ERROR [nio-9090-exec-7] c.b.g.c.CustomErrorController
MSG ==> [NOT FOUND 404] User [dumi7ru] tried to access this URL : [http://localhost:9090/error] : [null]