gpt4 book ai didi

java - 有没有办法在浏览器中实时查看我的网络应用程序 tomcat 日志?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:06:11 25 4
gpt4 key购买 nike

我正在使用 log4j 来记录我的数据。我希望能够在浏览器中与我的网络应用程序一起实时查看日志文件。有像 Chainsaw 这样的独立工具,它们非常好,但它们不能用于在浏览器中实时查看日志的目的。

谁能帮我解决这个问题?

最佳答案

一个简单的例子是:

Servlet(根据需要更改日志文件的路径):

@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 页面:

<!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>

关于java - 有没有办法在浏览器中实时查看我的网络应用程序 tomcat 日志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18369700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com