log4j study "23" Common Appender Socketappender

Source: Internet
Author: User
Tags object serialization

The previous appender are the file system-based Appender provided by LOG4J. Of course, in some special appender that need to be documented, we just need to choose a suitable appender to inherit and complete our own logic. About customizing Appender, see it later. Let's look at some of the more special Appender.

All of the previous appender have a common feature, is that they all need to configure a layout object, the following to introduce the Appender is very special, he does not need any layout object, this appender is Socketappender. Note that to be able to understand socketappender, you must have an understanding of Java network Programming and Java object Serialization.
As the name implies Socketappender is socket-based appender, he does not do any processing of log messages, but simply through the socket to send log requests to a specific server. Since the log request is sent to a particular server, the first thing to consider is how the log message is sent, in Socketappender, it simply sends the Loggingevent object directly to the socket's output stream in a serialized way. Therefore, to be able to use Socketappender, is not only the use of log applications, but also a unified and accept the log messages of the independent log server application. Here we simply call the application using the log function called the logging Client, and the server application that receives and processes the log messages is called Logging server.
To configure logging client side Appender This is not a difficult point, the following problem is that we need to write a logging server to receive our log messages. To accomplish such a server-side application, we first need to identify several requirements. First, what we read from the socket is the serialized Loggingevent object, so we have to deserialize the object first, get the Loggingevent object, and second, after we get this object, we want to determine the way to deal with this object, here we simply deal with it, Print out the log messages directly using System.out. So, we can write the framework code for this server first:
public static void Main (string[] args) throws Exception {
ServerSocket socket = new ServerSocket (4560);
while (true) {
Socket client = Socket.accept ();
Thread t = new Thread (new Logrunner (client));
T.start ();
}
}
We use a serversocket loop to listen on port 4560, after the request, the client request to a Logrunner thread to handle.
Here is the code for Logrunner:
Static Class Logrunner implements Runnable {
Private ObjectInputStream ois;

Public Logrunner (Socket client) {
try {
This.ois = new ObjectInputStream (Client.getinputstream ());
} catch (Exception e) {
}
}

@Override
public void Run () {
try {
while (true) {
Loggingevent event = (loggingevent) ois.readobject ();
System.out.println (Event.getloggername () + ":" + event.getmessage ());
}
} catch (Exception e) {
} finally {
}
}
}
Here are a few points to pay special attention to:
1, we use the inputstream of the socket to create a ObjectInputStream object that is used to deserialize the logging client sent Loggingevent.
2, in particular, we used a while (true) wireless loop in the Run method to continuously read in and convert the read-in binary content to object, and then turn the object into Loggingevent. Also, when we read a Loggingevent object, we do not close the ois. Why did you do it? In fact, we need to consider how Socketappender works. When a logging client runs, his corresponding Socketappender is started and a socket connection to the specified logging server is created. Whenever a log message arrives at Socketappender, it writes the serialized object data directly to the outputstream of the socket and sends it to the server side via flush. In other words, when a logging client application is created, it will always have a socket connected to the server, and the connection will not be broken, and the serialized data will be sent directly once a log message arrives. So on our server side, we have to maintain this connection after getting a socket connection, constantly reading the data from the connection, and cannot close the connection.
Then we'll run the app first. Look at the client again.
First look at Socketappender, he has a few common configurations:
RemoteHost: Specifies the address of the remote logging server. For example, for our application, it is possible to directly match localhost.
PORT: Specifies the ports of the remote logging server. Here, our server is listening on port 4560, so here's the 4560. In fact, by default, Socketappender is the requested port 4560.
Application: You can set the name of the app. Because using Socketappender, you can use the same dedicated logging server to complete the log records uniformly. Then there may be different applications to submit logs to the server, how to distinguish the log information is which client sent it? You can configure application information. How to obtain this information from Loggingevent, will be introduced later.
Reconnectiondelay: If the client connection is not on the server side, the connection will be reconnected after the specified time of Reconnectiondelay. One of the issues to note here is that the client sends a log request and a communication problem between the servers. In the case of normal network communication, each client's log request will be sent to the server-side processing, which is no problem. However, considering the instability of the network, the following conditions will occur:
1, when the network sends the packet frequency is larger than the log frequency, will normally send the information according to the log frequency;
2, when the network sends the packet frequency is lower than the log frequency, will only follow the network sends the packet frequency to send the client's log information. There may be a problem with the loss of log messages;
3, when the server connection is disconnected, Socketappender will attempt to reconnect to the server side, but during this disconnection, all log information will be lost.
Therefore, in the use of Socketappender, also need to take into account the network factors. Of course, we can also implement a appender, when the network is disconnected, the Loggingevent object is temporarily serialized to local, when the network is connected again, then the cache to the local Loggingevent object sent. To complete this function, just understand how the Appender works can be done more easily. We'll see about this later.
Next, complete the configuration of the client and run the test:
Log4j.rootlogger=debug,socket
Log4j.appender.socket=org.apache.log4j.net.socketappender
Log4j.appender.socket.remotehost=localhost
log4j.appender.socket.port=4560
Log4j.appender.socket.application=localclient
We defined a Socketappender, configured the server address and port number, and finally named our client localclient.
Here's a look at the test:
@Test
public void Testsocketappender () throws exception{
Logger Logger = Logger.getlogger ("Cd.itcast");
Logger Barlogger = Logger.getlogger ("Cd.itcast.log");
for (int i = 0; i <; i++) {
Logger.warn ("logger warn");
Logger.debug ("Logger Debug");
Barlogger.info ("Bar logger info");
Barlogger.debug ("Bar logger debug Long Long");
}
}
The same test, run 100 times, this time to run, you can see, the speed is very fast, the reason is that, using Socketappender, the client will not do any excessive processing on the loggingevent, and directly to the serialized object sent to the remote server, and, The logic of serialization and sending, or running independently in a separate thread, has no effect on the performance of the thread in which our application resides.
To view console output from the server side:
Localclient:cd.itcast:logger warn
Localclient:cd.itcast:logger Debug
Localclient:cd.itcast.log:bar Logger Info
Localclient:cd.itcast.log:bar Logger Debug Long Long
You can see the full output of the content.
In fact, we do not need to write this server-side application, because log4j for us to implement a server-side: Simplesocketserver.
This simplesocketserver is very simple to use, he is equivalent to the accepted loggingevent as a local logging event, and then use the server-side configuration of the log4j environment to log logs. Draw a simple diagram:

When starting the Simplesocketserver, there are two boot options, one is the listening port, and the other is the profile address, which we can test, First, create an additional log4j.properties file to control the LOG4J environment above the simplesocketserver.
Log4j.rootlogger=debug,file
Log4j.appender.file=org.apache.log4j.fileappender
Log4j.appender.file.layout=org.apache.log4j.patternlayout
log4j.appender.file.layout.conversionpattern=%r [%t]%p%c%x-%m%n
Log4j.appender.file.file=serverlog.log
We name this configuration file log4jserver.properties,
Then use the parameter 4560 log4jserver.properties to start the simplesocketserver.
Run our test again, you can find that in the application directory, more log4jserver.log log files, and the contents of the inside:
0 [main] INFO org.apache.log4j.net.simplesocketserver-listening on port 4560
0 [main] INFO org.apache.log4j.net.simplesocketserver-waiting to accept a new client.
29968 [main] INFO org.apache.log4j.net.simplesocketserver-connected to client at/192.168.1.101
29968 [main] INFO org.apache.log4j.net.simplesocketserver-starting new socket node.
29968 [main] INFO org.apache.log4j.net.simplesocketserver-waiting to accept a new client.
87406 [main] INFO org.apache.log4j.net.simplesocketserver-connected to client at/192.168.1.101
87406 [main] INFO org.apache.log4j.net.simplesocketserver-starting new socket node.
87422 [main] INFO org.apache.log4j.net.simplesocketserver-waiting to accept a new client.
87422 [main] WARN Cd.itcast-logger WARN
87437 [main] Debug Cd.itcast-logger debug
87437 [main] info Cd.itcast.log-bar logger info
87437 [main] Debug Cd.itcast.log-bar logger debug Long Long
is indeed a log message for our client.

About Appender, we will see here for a moment, as for the back of the Smtpappender and Jdbcappender, we follow the idea of learning these appender, to use it.

log4j study "23" Common Appender Socketappender

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.