JAVA读取tomcat日志
添加maven依赖
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
建立socket
package com.ghgcn.cigarbox.manager.action;
import java.io.InputStream;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ghgcn.cigarbox.manager.thread.TailLogThread;
import com.ghgcn.cigarbox.support.SysParam;
/**
*
* @ClassName: LogWebSocketHandle
* @Description: TODO(这里用一句话描述这个类的作用)
* @author 刘楠
* @date 2017年9月11日 下午7:17:03
*
*/
@ServerEndpoint("/sys/log")
public class LogWebSocketHandle {
private Logger logger =LoggerFactory.getLogger(LogWebSocketHandle.class);
private Process process;
private InputStream inputStream;
/**
* 开启websocket
* Description :
* @param session
*/
@OnOpen
public void onOpen(Session session){
try {
logger.debug("=========================开启websocket========================================");
//执行tail -f 命令
process = Runtime.getRuntime().exec("tail -f "+SysParam.gettomcatLog());
inputStream = process.getInputStream();
//一定要启动新线程,防止inputstream 阻塞处理websocket的线程
TailLogThread thread = new TailLogThread(inputStream, session);
thread.start();
} catch (Exception e) {
//e.printStackTrace();
logger.debug("onOpen {}",e.getMessage());
}
}
/**
* 关闭websocket
* Description :
*/
@OnClose
public void onClose(){
logger.debug("=========================关闭websocket========================================");
try {
if(inputStream != null){
inputStream.close();
}
} catch (Exception e) {
//e.printStackTrace();
logger.debug("onClose {}",e.getMessage());
}
if(process != null){
process.destroy();
}
}
@OnError
public void onError(Throwable thr){
//thr.printStackTrace();
logger.debug("onError {}",thr.getMessage());
}
}
建立线程
package com.ghgcn.cigarbox.manager.thread;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.websocket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ghgcn.cigarbox.manager.action.LogWebSocketHandle;
/**
*
* @ClassName: TailLogThread
* @Description: TODO(这里用一句话描述这个类的作用)
* @author 刘楠
* @date 2017年9月11日 下午7:16:55
*
*/
public class TailLogThread extends Thread{
private BufferedReader reader;
private Session session;
private Logger logger =LoggerFactory.getLogger(TailLogThread.class);
public TailLogThread(InputStream in, Session session) {
this.reader = new BufferedReader(new InputStreamReader(in));
this.session = session;
}
@Override
public void run() {
logger.debug("============thread start===============");
String line;
try {
while((line = reader.readLine()) != null){
//将实时日志通过websocket发送到客户端,给每一行添加一个HTML换行
session.getBasicRemote().sendText(line + "<br>");
}
} catch (Exception e) {
//e.printStackTrace();
logger.debug("TailLogThread run {}",e.getMessage());
}
super.run();
}
}
前端 页面 index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<% String ctx = request.getContextPath();
pageContext.setAttribute("ctx", ctx);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>log</title>
<script type="text/javascript" src="./common/js/jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="log-container" style="height:900px; overflow-y:scroll; background:#333; color:#aaa; padding:10px">
<div></div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
//alert('${ctx}');
//指定websocket路径
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
//websocket = new WebSocket("ws://mt.zpcx.cn/tomcatLog/log");
websocket = new WebSocket("ws://"+location.host+"${ctx}"+"/log");
}else{
alert('Not support websocket')
}
//连接成功建立的回调方法
websocket.onopen = function(event){
//alert("open");
}
websocket.onmessage = function(event){
//接收服务端的实时日志并添加到HTML页面中
$("#log-container div").append(event.data);
//滚动条滚动到最底部
$("#log-container").scrollTop($("#log-container div").height() - $("#log-container").height());
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
})
</script>
</html>
访问
Paste_Image.png
网友评论