docker日志,Linux日志持续读取显示

该代码实现了一个名为LogView的类,用于实时显示日志文件的内容。它使用RandomAccessFile来跟踪文件的大小,并通过ScheduledExecutorService每3秒检查一次新添加的日志行。这些行通过StargoLogWebSocket类发送到WebSocket客户端,该类管理着客户端连接,接收并处理来自客户端的消息。
摘要由CSDN通过智能技术生成
package com.skyable.deploy.utils;

import com.skyable.deploy.handler.StargoLogWebSocket;
import org.springframework.scheduling.annotation.Async;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/** 实时显示日志 */
public class LogView {
  private long lastTimeFileSize = 0; // 上次文件大小
  /**
   * 实时输出日志信息
   *
   * @param logFile 日志文件
   * @throws IOException
   */
  @Async
  public void realtimeShowLog(File logFile, Integer clusterId) throws IOException {
    // 给文件增加读写权限
    final RandomAccessFile randomFile = new RandomAccessFile(logFile, "rw");
    // 启动一个线程每5秒钟读取新增的日志信息
    ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
    exec.scheduleWithFixedDelay(
        new Runnable() {
          @Override
          public void run() {
            try {
              // 获得变化部分的
              randomFile.seek(lastTimeFileSize);
              String tmp = "";
              while ((tmp = randomFile.readLine()) != null) {
                StargoLogWebSocket.sendMessage(clusterId, new String(tmp.getBytes("ISO8859-1")));
                System.out.println(new String(tmp.getBytes("ISO8859-1")));
              }
              lastTimeFileSize = randomFile.length();
            } catch (IOException e) {
              throw new RuntimeException(e);
            }
          }
        },
        0,
        3,
        TimeUnit.SECONDS);
  }

  public static void main(String[] args) throws Exception {
    LogView view = new LogView();
    final File tmpLogFile = new File("C:\\Users\\Administrator\\Desktop\\cluster-91.yaml");
    view.realtimeShowLog(tmpLogFile, 1);
  }
}
package com.skyable.deploy.handler;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ServerEndpoint(value = "/stargoLog/{clusterId}")
@Component
public class StargoLogWebSocket {
    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static AtomicInteger ONLINE_COUNT = new AtomicInteger(0);

    /**
     * concurrent包的线程安全Map,用来存放每个客户端对应的Session对象。
     */
    private static Map<Integer,Session> WEBSOCKET_MAP = new ConcurrentHashMap<>();

    /**
     * 客户端标识
     */
    private Integer clusterId;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("clusterId") Integer clusterId) {
        this.clusterId = clusterId;
        WEBSOCKET_MAP.put(clusterId,session);
        //统计当前在线的虚拟设备数量
        addOnlineCount();
        log.info("stargo log websocket connect ok! {}", getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        WEBSOCKET_MAP.remove(this.clusterId);
        subOnlineCount();
        log.info("stargo log websocket disconnect {}", getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("receive message from client {} and message is {}", session.getId(), message);
    }


    @OnError
    public void onError(Session session, Throwable error) {
        log.error("client {} has an error {}", session.getId(), error.getMessage());
    }

    public static void sendMessage(Integer clusterId, Object message) {
        //this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
        Session session = WEBSOCKET_MAP.get(clusterId);
        if(session != null) {
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(message));
            } catch (IOException e) {
                log.error("send message to web error ", e);
            }
        }
    }

    private static synchronized int getOnlineCount() {
        return ONLINE_COUNT.get();
    }

    private static synchronized void addOnlineCount() {
        ONLINE_COUNT.incrementAndGet();
    }

    private static synchronized void subOnlineCount() {
        ONLINE_COUNT.decrementAndGet();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值