引入依赖
<!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.2</version> </dependency>
在resouces下加入log4.properties文件
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.err log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=d:\mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### ### fatal error warn info debug trace log4j.rootLogger=all, stdout
编写测试文件Log4jTest和Slf4jTest
import org.apache.log4j.Logger; import org.junit.Test; public class Log4jTest { // apache-log4j日志 private final Logger LOGGER = Logger.getLogger(Log4jTest.class); /** * apache-log4j 日志输出 */ @Test public void testLog4j(){ LOGGER.info("普通信息"); LOGGER.error("普通错误"); LOGGER.trace("堆栈信息"); LOGGER.fatal("致命错误"); LOGGER.warn("警告信息"); LOGGER.debug("调试信息"); } }
import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Slf4j public class Slf4jTest { private final Logger logger = LoggerFactory.getLogger(Slf4jTest.class); /** * apache-log4j 日志输出 */ @Test public void testLog4j(){ logger.info("普通信息"); logger.error("普通错误"); logger.trace("堆栈信息"); logger.warn("警告信息"); logger.debug("调试信息"); } /** * lombok 注解日志输出 */ @Test public void testLombok(){ log.info("普通信息"); log.error("普通错误"); log.trace("堆栈信息"); log.warn("警告信息"); log.debug("调试信息"); } }