I am using log4j to log my data. I wan to be able to view the log files realtime alongside my web-app in a browser. There are standalone tools like Chainsaw which are quite good, but they don't serve the purpos eof viewing logs real-time in a browser.
Can anybody help me with this?
A simple example would be:
Servlet (change path of log file as needed):
@WebServlet(name = "Log", urlPatterns = { "/log" })
public class LogServlet extends HttpServlet {
private static final long serialVersionUID = 7503953988166684851L;
public LogServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Path path = FileSystems.getDefault()
.getPath("/path/to/tomcat/logs", "catalina.out");
StringBuilder logContent = new StringBuilder();
logContent.append("<pre>");
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);) {
String line = null;
while ((line = reader.readLine()) != null) {
logContent.append(line).append("<br/>");
}
} catch (IOException x) {
// Take care of that
}
logContent.append("</pre>");
resp.getWriter().print(logContent.toString());
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
}
}
HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Log viewer</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write(unescape('%3Cscript src="http://jquery.com/jquery-wp-content/themes/jquery/js/jquery-1.10.2.min.js"%3E%3C/script%3E'))
</script>
<script type="text/javascript">
var logging = false;
function refreshLog() {
if (logging) {
$.get('/log', function(data) {
$('#log').html(data);
});
}
if (logging) {
setTimeout(function() {
refreshLog()
}, 5000);
}
}
function toggleLogs() {
if (logging) {
logging = false;
$("#tog").val("Start");
} else {
logging = true;
$("#tog").val("Stop");
refreshLog();
}
}
</script>
</head>
<body style="width: 100%; padding: 0; margin: 0">
<input type="button" id="tog" onclick="toggleLogs()" value="Start" />
<div id="log" style="width: 100%; padding: 0; margin: 0"></div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With