国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java javaTutorial Java and WebSocket: How to implement real-time log monitoring

Java and WebSocket: How to implement real-time log monitoring

Dec 17, 2023 pm 09:10 PM
java websocket real time monitoring

Java and WebSocket: How to implement real-time log monitoring

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to iterate over a Map in Java? How to iterate over a Map in Java? Jul 13, 2025 am 02:54 AM

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)-&gt

Comparable vs Comparator in Java Comparable vs Comparator in Java Jul 13, 2025 am 02:31 AM

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

How to handle character encoding issues in Java? How to handle character encoding issues in Java? Jul 13, 2025 am 02:46 AM

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

How does a HashMap work internally in Java? How does a HashMap work internally in Java? Jul 15, 2025 am 03:10 AM

HashMap implements key-value pair storage through hash tables in Java, and its core lies in quickly positioning data locations. 1. First use the hashCode() method of the key to generate a hash value and convert it into an array index through bit operations; 2. Different objects may generate the same hash value, resulting in conflicts. At this time, the node is mounted in the form of a linked list. After JDK8, the linked list is too long (default length 8) and it will be converted to a red and black tree to improve efficiency; 3. When using a custom class as a key, the equals() and hashCode() methods must be rewritten; 4. HashMap dynamically expands capacity. When the number of elements exceeds the capacity and multiplies by the load factor (default 0.75), expand and rehash; 5. HashMap is not thread-safe, and Concu should be used in multithreaded

What is the 'static' keyword in Java? What is the 'static' keyword in Java? Jul 13, 2025 am 02:51 AM

InJava,thestatickeywordmeansamemberbelongstotheclassitself,nottoinstances.Staticvariablesaresharedacrossallinstancesandaccessedwithoutobjectcreation,usefulforglobaltrackingorconstants.Staticmethodsoperateattheclasslevel,cannotaccessnon-staticmembers,

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

What is a ReentrantLock in Java? What is a ReentrantLock in Java? Jul 13, 2025 am 02:14 AM

ReentrantLock provides more flexible thread control in Java than synchronized. 1. It supports non-blocking acquisition locks (tryLock()), lock acquisition with timeout (tryLock(longtimeout, TimeUnitunit)) and interruptible wait locks; 2. Allows fair locks to avoid thread hunger; 3. Supports multiple condition variables to achieve a more refined wait/notification mechanism; 4. Need to manually release the lock, unlock() must be called in finally blocks to avoid resource leakage; 5. It is suitable for scenarios that require advanced synchronization control, such as custom synchronization tools or complex concurrent structures, but synchro is still recommended for simple mutual exclusion requirements.

See all articles