Java uses WebSocket + tail commands to implement real-time Web logs

Source: Internet
Author: User

Java uses WebSocket + tail commands to implement real-time Web logs

In Linux, you often need to view the Real-Time Output content of log files.tail -fOrtaifCommand. To view Real-time logs, you may need to first connect to the Linux host through SSH. The steps are troublesome. If the server is in the production environment, various permissions may be controlled. Web-based Real-time logs can solve this problem.

Because the traditional HTTP protocol is the request/response mode, and real-time logs require continuous output from time to time, the server actively pushes the logs to the client browser. So here we use the HTML5 WebSocket protocol.

According to the Convention, first:

Java background

JSR 356 is a set of Java-based WebSocket specifications. Therefore, a server that supports JSR 356, such as the latest version of Tomcat and Jetty, is required.

JSR 356 provides annotations@ServerEndpointAnd you must specify a path to process WebSocket requests from the client.

Import java. io. IOException; 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; @ ServerEndpoint ("/log") public class LogWebSocketHandle {private Process process; private InputStream inputStream; /*** enable the new WebSocket Request */@ OnOpen public void onOpen (Session sess Ion) {try {// execute the tail-f command process = runtime.getruntime(cmd.exe c ("tail-f/var/log/syslog"); inputStream = process. getInputStream (); // you must start a new thread to prevent InputStream from blocking the thread that processes WebSocket. TailLogThread thread = new TailLogThread (inputStream, session); thread. start ();} catch (IOException e) {e. printStackTrace () ;}/ *** WebSocket request closed */@ OnClose public void onClose () {try {if (inputStream! = Null) inputStream. close ();} catch (Exception e) {e. printStackTrace ();} if (process! = Null) process. destroy () ;}@ OnError public void onError (Throwable thr) {thr. printStackTrace ();}}

Because a new LogWebSocketHandle instance is created for each WebSocket connection, thread security issues do not need to be considered like Servlet. Becausetail -fThe input stream of the command will block the current thread, so you must create a new thread to readtail -fCommand.

Import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import javax. websocket. session; public class TailLogThread extends Thread {private BufferedReader reader; private Session session; 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) {// send real-time logs to the client through WebSocket, and add an HTML newline session. getBasicRemote (). sendText (line +"
") ;}} Catch (IOException e) {e. printStackTrace ();}}}

BecausetailThe Java server must be deployed on the Linux system.

Web Front-end

  Tail log<Script src = "// cdn.bootcss.com/jquery/2.1.4/jquery.js"> </script>                        <Script> $ (document ). ready (function () {// specify the websocket path var websocket = new WebSocket ('ws: // localhost: 8080/log'); websocket. onmessage = function (event) {// receives real-time logs from the server and adds them to the HTML page $ ("# log-container div "). append (event. data); // scroll to the lowest part of the scroll bar $ ("# log-container "). scrollTop ($ ("# log-container div "). height ()-$ ("# log-container "). height () ;};}); </script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.