With the advent of the Internet era, real-time communication has become an indispensable part of modern software development. WebSocket is a full-duplex communication protocol that allows the front-end and back-end to communicate in real time, which greatly facilitates the implementation of the important function of real-time log monitoring. In this article, I will introduce you to how Java and WebSocket implement real-time log monitoring, and provide practical code examples to help you better understand.
Step one: Build a WebSocket environment
First, you need to introduce relevant dependencies, including Java WebSocket and log4j2. We can manage these dependencies through Maven, as follows:
<dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.11.2</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.11.2</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>2.11.2</version> </dependency>
Next, create the WebSocket Server-side code, as follows:
@ServerEndpoint("/log") public class WebSocketServer { private static final Logger logger = LogManager.getLogger(WebSocketServer.class.getName()); @OnOpen public void onOpen(Session session) { logger.info("WebSocket opened: " + session.getId()); } @OnClose public void onClose(Session session) { logger.info("WebSocket closed: " + session.getId()); } @OnError public void onError(Session session, Throwable throwable) { logger.error("WebSocket error: " + throwable.getMessage()); } @OnMessage public void onMessage(String message) { logger.info("WebSocket received message: " + message); } public void sendMessage(String message) { try { for (Session session : this.sessions) { if (session.isOpen()) { session.getBasicRemote().sendText(message); } } } catch (Exception e) { logger.error("WebSocket send message error: " + e.getMessage()); } } }
In the above code, we use the annotation @ServerEndpoint to define a WebSocket server can receive connection requests from clients. After the connection is successfully established, the @OnOpen method will be called. When the connection is closed, the @OnClose method is called. When an error occurs, the @OnError method is called. When the server receives the information sent by the client, it calls the @OnMessage method for processing. In addition, we also implemented a sendMessage method for sending information to the client.
Step 2: Implement log monitoring
Next, we need to implement the specific log monitoring function. Here we take log4j2 as an example to monitor the specified log file. First, you need to add an Appender to the log4j2 configuration file to output the log to a specified file.
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="INFO"> <Appenders> <RollingFile name="RollingFile" fileName="logs/app.log" filePattern="${sys:logPath}/app-%d{MM-dd-yyyy}-%i.log.gz" ignoreExceptions="false"> <PatternLayout> <pattern>%d %p %c{1.} [%t] %m%n</pattern> </PatternLayout> <Policies> <SizeBasedTriggeringPolicy size="64 MB" /> </Policies> <DefaultRolloverStrategy max="10" /> </RollingFile> </Appenders> <Loggers> <Logger name="com.your.package" level="debug" additivity="false"> <AppenderRef ref="RollingFile" /> </Logger> <Root level="info"> <AppenderRef ref="RollingFile" /> </Root> </Loggers> </Configuration>
In Appender, we set fileName to logs/app.log, which means that the log will be output to the specified file. Next, we need to write a class to implement the FileTailer interface in log4j2 and monitor log file changes.
public class FileTailerListener implements FileTailer { private static final Logger logger = LogManager.getLogger(FileTailerListener.class.getName()); private WebSocketServer webSocketServer; public FileTailerListener(WebSocketServer webSocketServer) { this.webSocketServer = webSocketServer; } @Override public void handle(String line) { logger.info(line); this.webSocketServer.sendMessage(line); } }
In the above code, we implemented the FileTailer interface and defined the handle method to monitor the log file. At the same time, we call the sendMessage method in WebSocketServer to send the log information to the client.
Step Three: Start WebSocket Server and Log Monitor
After completing the writing of WebSocket Server and log monitor, we need to start them in the application. We can start the WebSocket Server and FileTailerListener respectively at startup, as follows:
public class Application { public static void main(String[] args) { try { WebSocketServer webSocketServer = new WebSocketServer(); FileTailerListener fileTailerListener = new FileTailerListener(webSocketServer); FileTailerService fileTailerService = new FileTailerService(); fileTailerService.addListener(fileTailerListener); fileTailerService.start(new File("logs/app.log")); ServerEndpointConfig.Builder.create(WebSocketServer.class, "/log") .configurator(new ServerEndpointConfig.Configurator()) .build(); Server server = new Server(8080); server.setHandler(new WebSocketHandler(webSocketServer)); server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); } } }
In the above code, we start the FileTailerService to monitor log file changes and register the FileTailerListener to the Service. At the same time, a Jetty Server is started to handle WebSocket connection requests.
Step 4: Write the front-end code
Looking back at the previous code, we have set up a WebSocket environment and implemented log monitoring and sending. Finally, we need to write front-end code to display and update log information in real time. Here, we can use JavaScript to complete front-end development. The specific code is as follows:
var webSocket = new WebSocket("ws://localhost:8080/log"); webSocket.onopen = function(event) { console.log("WebSocket opened"); }; webSocket.onmessage = function(event) { var message = event.data; var logContainer = document.getElementById("logContainer"); var textNode = document.createTextNode(message); logContainer.appendChild(textNode); logContainer.scrollTop = logContainer.scrollHeight; }; webSocket.onclose = function(event) { console.log("WebSocket closed"); }; webSocket.onerror = function(event) { console.error("WebSocket error: " + event); };
In the code, we use the WebSocket object to establish the connection, and when receiving the message sent by the server, dynamically add the message to page. At the same time, we use the scrollTop attribute to keep the log information scrolling.
At this point, we have completed the process of implementing real-time log monitoring with Java and WebSocket. Through the above code examples, you can learn how to use Java and WebSocket to implement real-time log monitoring, and also learn how to monitor log files and use WebSocket.
The above is the detailed content of Java and WebSocket: How to implement real-time log monitoring. For more information, please follow other related articles on the PHP Chinese website!