Log4j2 test instance-socket centralized print example, log4j2-socket
1. Background
Because the company recently set up a centralized log management platform and required that all system logs be sent to the unified platform, based on this, we studied the socket of log4j2.
2. Prepare materials
Two jar packages for log4j2: log4j-api-2.1.jar and log4j-core-2.1.jar. (The version must be consistent, especially the jar on the server and the jar on the client)
3. log4j2 client Configuration
Directly create a java project in IDE. Add the log4j2. xml file under the src root directory.
1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <Configuration> 3 <Appenders> 4 <Socket name = "socket" host = "IP" port = "8086"> 5 <SerializedLayout/> 6 </Socket> 7 <! -- In ide, print to Console --> 8 <console name = "Console" target = "SYSTEM_OUT"> 9 <PatternLayout pattern = "% d %-5 p [% t] % C {2} (% F: % L) -% m % n "/> 10 </Console> 11 </Appenders> 12 <Loggers> 13 <Root level =" info "> 14 <AppenderRef ref =" socket "/> 15 <AppenderRef ref = "console"/> 16 </Root> 17 <Logger name = "app" level = "info" additi.pdf = "false"> 18 <AppenderRef = "socket"/> 19 </Logger> 20 </Loggers> 21 </Configuration>
Log4j2. xml
Create a client to test the java class Log4j2SocketTest
1 import org.apache.logging.log4j.LogManager; 2 import org.apache.logging.log4j.core.Logger; 3 4 public class Log4j2SocketTest { 5 static Logger logger = (Logger) LogManager.getLogger("app"); 6 static Logger logger_default = (Logger) LogManager.getLogger(); 7 8 public static void main(String[] args) { 9 logger.debug("logger.debug....");10 logger.info("logger.info....");11 System.out.println("another");12 logger_default.debug("logger_default.debug");13 logger_default.info("logger_default.info");14 }15 }
Log4j2SocketTest4 and log4j2 server receive LOG simulator Configuration
This is only a simulated receiving server. It is used to print the received content to a file so that you can view the content sent from the client.
Put these three files in the same directory: log4j-api-2.1.jar, log4j-core-2.1.jar, and log4j2. xml
1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <Configuration> 3 <Appenders> 4 <! -- Console output --> 5 <File name = "MyFile" fileName = "D:/logs/log. log "> 6 <PatternLayout pattern =" % d {HH: mm: ss. SSS} [% t] %-5 level % C {2} (% F: % L) % L-% msg % n "/> 7 </File> 8 </Appenders> 9 <Loggers> 10 <Root level =" debug "> 11 <AppenderRef ref =" MyFile "/> 12 <AppenderRef ref =" STDOUT "/> 13 </Root> 14 </Loggers> 15 </Configuration>
Log4j2. xml
After these three files are put in place, we start the server as follows:
Java-cp log4j-api-2.2.jar; log4j-core-2.2.jar org.apache.logging.log4j.core.net. server. TcpSocketServer 8085 log4j2. xml
Note: Use the colon ':' between jar files in linux and the comma ';' for windows ';'
5. You can print the client logs in the ide and upload them to the server.