websocket在前端展示后端日志

最近在写平台收到一个需要看后台运行日志的需求,所以查看了下使用websocket来写。主要思想就是使用Linux的tail指令进行实时日记读取,然后在进行与界面通信展示的过程。

第一步

添加pom依赖:

    org.springframework.boot

    spring-boot-starter-websocket

第二步

定义一个Bean

@Component

public class WebSocketConfig {

    @Bean

    public ServerEndpointExporter serverEndpointExporter(){

        return new ServerEndpointExporter();

    }

}

第三步

这里可以实现两种方式:

一种方式是实时进行打印展示日志,不进行写文件,然后使用tail方式读取;

两外一种方式就是进行写文件,然后使用tail方式读取文件方式(可以直接跳过此步,直接看第四步)。

这两种方式各有优缺点:

1、第一种

优点:实时打印,不需要进行写文件的操作

缺点:界面刷新后日志丢失,无法重现,需要进行一个长链接处理

2、第二种

优点:界面刷新或者关闭重开不影响日志的显示,且日志保存在磁盘中

缺点:需要额外的空间写文件,其他暂未发现

先说说第一种方式,这里需要创建一个service:

@Service

@Slf4j

public class WebLogsService {

    @Autowired private WebSocket webSocket;

    public String output(String message) {

         webSocket.sendMessage(message);

        return "测试";

    }

}

这里主要用来进行一个调用触发日志打印的。第二种方式放在第四步来讲。

第四步

写一个前端websocket来接受后端websocket,这也是一个Controller,但比较特殊,是用WS协议进行通信的。

这里分两个写法:

第一种,对应第三步里的第一种

@Component

@ServerEndpoint("/webSocket/{param}") 

@Slf4j

public class WebSocket {

    private Session session;

    private Process process;

    private InputStream inputStream;

    private static CopyOnWriteArraySet webSocketSet=new CopyOnWriteArraySet<>();

    @OnOpen

public void onOpen(Session session){

        this.session=session;

        webSocketSet.add(this);

        log.info("【websocket消息】 有新的连接,总数:{}",webSocketSet.size());

}

@OnClose

public void onClose(){

    webSocketSet.remove(this);

    log.info("【websocket消息】 连接断开,总数:{}",webSocketSet.size());

    try {

        if(inputStream != null) inputStream.close();

    } catch (Exception e) {

        e.printStackTrace();

    }

    if (process != null)

        process.destroy();

}

@OnMessage

public void onMessage(String message){

    log.info("【websocket消息】 收到客户端发来的消息:{}",message);

}

public void sendMessage(String param){

    for(WebSocket webSocket:webSocketSet){

        log.info("【websocket消息】 广播消息,message={}",param);

        try {

            webSocket.session.getBasicRemote().sendText(param);

        }catch (Exception e){

            e.printStackTrace();

            }

        }

    }

}

第二种,对应第三步里的第二种

@Component

@ServerEndpoint("/webSocket/{param}")

@Slf4j

public class WebSocket {

private Sessionsession;

private Processprocess;

private InputStreaminputStream;

private static CopyOnWriteArraySetwebSocketSet=new CopyOnWriteArraySet<>();

@OnOpen

    public void onOpen(Session session,@PathParam("param") String param){

this.session=session;

webSocketSet.add(this);

log.info("【websocket消息】 有新的连接,总数:{}",webSocketSet.size());

try {

// 执行tail -f命令

            process = Runtime.getRuntime().exec("tail -f /log/" + param +".txt");

inputStream =process.getInputStream();

// 一定要启动新的线程,防止InputStream阻塞处理WebSocket的线程

            TailLogThread thread =new TailLogThread(inputStream, session);

thread.start();

}catch (IOException e) {

e.printStackTrace();

}

}

@OnClose

    public void onClose(){

webSocketSet.remove(this);

log.info("【websocket消息】 连接断开,总数:{}",webSocketSet.size());

try {

if(inputStream !=null)

inputStream.close();

}catch (Exception e) {

e.printStackTrace();

}

if(process !=null)

process.destroy();

}

@OnMessage

    public void onMessage(String message){

log.info("【websocket消息】 收到客户端发来的消息:{}",message);

}

}

选择第二种还需要提供线程机制

public class TailLogThreadextends Thread {

private BufferedReaderreader;

private Sessionsession;

public TailLogThread(InputStream in, Session session) {

this.reader =new BufferedReader(new InputStreamReader(in));

this.session = session;

}

@Override

  public void run() {

String line;

try {

while((line =reader.readLine()) !=null) {

// 将实时日志通过WebSocket发送给客户端,给每一行添加一个HTML换行

            session.getBasicRemote().sendText(line);

}

}catch (IOException e) {

e.printStackTrace();

}

}

}

第五步

前端开发


这里的参数param就是你在磁盘内创建的日志文件。


参考:

https://blog.csdn.net/sihai12345/article/details/80924937

你可能感兴趣的:(websocket在前端展示后端日志)