在Maven 项目中 pom.xml 中添加Log4j2 的依赖
<dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.14.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-1.2-api</artifactId> <version>2.14.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-jul</artifactId> <version>2.14.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.14.1</version> </dependency> <!-- 添加 Log4j2 SocketAppender 所需的依赖 --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.14.1</version> <classifier>udp</classifier> </dependency>
log4j2的配置文件 log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Socket name="UdpAppender" host="localhost" port="8101" protocol="udp"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/> </Socket> </Appenders> <Loggers> <Root level="debug"> <AppenderRef ref="UdpAppender"/> </Root> </Loggers> </Configuration>
log4j2.xml 位置
调用方法
package com.MyLogHelper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class App { private static final Logger logger = LogManager.getLogger(App.class); public static void main( String[] args ) { System.out.println( "Hello World!" ); logger.debug("This is a debug message"); logger.info("This is an info message"); logger.warn("This is a warn message"); logger.error("This is an error message"); logger.fatal("This is a fatal message"); } }
这样就可以将Log4j2日志内容输出到 localhost 的 8101 端口上
标签:udp,java,message,logging,apache,org,logger,Log4j2,log4j From: https://www.cnblogs.com/hailexuexi/p/18510807