Skip to content

Instantly share code, notes, and snippets.

@helospark
Created September 18, 2017 08:09
Show Gist options
  • Save helospark/087d827aad55190fac7c6f1f50b4ac77 to your computer and use it in GitHub Desktop.
Save helospark/087d827aad55190fac7c6f1f50b4ac77 to your computer and use it in GitHub Desktop.
Expose a log file via HTTP
package com.example;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
/**
* Quick solution to exposes log files via HTTP.
* Usage: localhost:8080/customLogFile?path=tomcat_access.log
* You have to define logfile.expose.enabled for it to work
*/
@Controller
@ConditionalOnProperty(value = "logfile.expose.enabled", matchIfMissing = false)
public class LogFileExposer {
@RequestMapping("/customLogFile")
public void handle(@RequestParam("path") String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File file = new File("logs"); // root path
String fileName = (new File(path)).getName();
File fullPath = new File(file, fileName);
Resource resource = new FileSystemResource(fullPath);
if (!resource.exists()) {
throw new IllegalArgumentException("Resource does not exist");
}
Handler handler = new Handler(resource, request.getServletContext());
handler.handleRequest(request, response);
}
private static class Handler extends ResourceHttpRequestHandler {
private final Resource resource;
Handler(Resource resource, ServletContext servletContext) {
this.resource = resource;
getLocations().add(resource);
try {
setServletContext(servletContext);
afterPropertiesSet();
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
@Override
protected void initAllowedLocations() {
this.getLocations().clear();
}
@Override
protected Resource getResource(HttpServletRequest request) throws IOException {
return this.resource;
}
@Override
protected MediaType getMediaType(Resource resource) {
return MediaType.TEXT_PLAIN;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment