log-view-platform 日志可视化平台
实现:
1.搭建springboot项目,配置好webscoket服务。引入相应的依赖
2.通过webscoket+ Runtime.getRuntime().exec(cmds);+ tail 命令实现日志查询(弃用)
3.通过webscoket+ 直接连接服务器 tail 命令实现日志查询
运行:
1.修改ws接口的ip为本机或者部署的服务器ip,
2.修改LogWebSocketHandle_v2类中需要查询的服务器ip+port+user+password
3.将文件打成jar包 通过Java -jar 命令直接启动
遇到的问题:
1.代码是部署在生产服务器,本地环境怎么访问?
在能访问到的服务器上(线下服务器)配置好ng转发,包括http的以及webscoket的
server {
##监听本机的那个端口,我的项目开启的是10001端口
listen 10001;
server_name localhost;
proxy_set_header X-Real_IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X_Forward_For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
location / {
##将本机的10001的所有请求转发到以下服务器
proxy_pass http://ip:port/;
}
}
2.在Java通过Runtime.getRuntime().exec(cmd);执行含有管道符命令的时候,直接查不出数据,类似 tail -f /log/a.logs |grep name
需要使用exec重载方法, String[] cmds = {"/bin/sh","-c",cmd}; 即可,不过还是会遇到查不出数据的情况
3.Runtime.getRuntime().exec(cmds) 按照上面的情况修改后 还是会出现查不出数据的时候, 类似 |grep na 能查出,但是|grep name 查不出(直接在服务器是能查到的)
将Runtime.getRuntime().exec(cmds); 改为直接连接服务器的方法
ch.ethz.ssh2.Session session = null;
connection = new ch.ethz.ssh2.Connection("ip",port);
// 建立连接,如果没有此步骤会报Connection is not established!链接未建立
connection.connect();
// 校验权限
connection.authenticateWithPassword("账号", "密码");
session = connection.openSession();
// 执行命令
session.execCommand(sb.toString());
// 获取执行命令输出的信息
InputStream stdout = session.getStdout();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stdout, charsetString));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// 将实时日志通过WebSocket发送给客户端,给每一行添加一个HTML换行
session.getBasicRemote().sendText(line + "<br>");
}
4.Message will not be sent because the WebSocket session has been closed
产生原因:同时有多个线程调用了this.session.getBasicRemote().sendText(msg);或者是已经关闭了流,却还在调用该方法
解决:使用线程安全的集合+在释放资源的时候需要先释放连接connect再去释放流就行了,不过网上遇到的解决方法是加锁,https://www.jianshu.com/p/888cbcf173ae
源码地址:https://github.com/GdHuni/log-view-platform.git