今天完成最后一篇文章的介绍,也就是我们的log4j2。
log4j2的优点笔者就不再介绍了,网上一大堆相关文章。简单粗暴点,我们直接上使用。
org.apache.logging.log4j
log4j-core
2.5
D:/
%d %p %C{} [%t] %m%n
%d %p %C{} [%t] %m%n
%d %p %C{} [%t] %m%n
%d %p %C{} [%t] %m%n
%d %p %C{} [%t] %m%n
需要注意的是,上述文件配置方式为同步
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LogTest {
private static final Logger logger = LogManager.getLogger(LogTest.class);
public static void main(String[] args) {
logger.debug("debug msg");
logger.info("info msg");
logger.warn("warn msg");
logger.error("error msg");
}
}
2022-04-09 12:37:54,919 DEBUG [main] com.log.test.LogTest: debug msg
2022-04-09 12:37:54,921 INFO [main] com.log.test.LogTest: info msg
2022-04-09 12:37:54,921 WARN [main] com.log.test.LogTest: warn msg
2022-04-09 12:37:54,922 ERROR [main] com.log.test.LogTest: error msg
org.apache.logging.log4j
log4j-core
2.5
org.apache.logging.log4j
log4j-slf4j-impl
2.5
org.slf4j
slf4j-api
1.7.12
log4j-slf4j-impl即slf4j对log4j2的桥接类,版本与log4j-core保持一致即可
而slf4j-api的版本,可以通过log3j-slf4j-impl版本来确认
同1.2
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Log_slf4j_Test {
private static Logger logger = LoggerFactory.getLogger(Log_slf4j_Test.class);
public static void main(String[] args) {
logger.debug("debug msg");
logger.info("info msg");
logger.warn("warn msg");
logger.error("error msg");
}
}
2022-04-09 12:41:18,471 DEBUG [main] com.log.test.Log_slf4j_Test: debug msg
2022-04-09 12:41:18,472 INFO [main] com.log.test.Log_slf4j_Test: info msg
2022-04-09 12:41:18,473 WARN [main] com.log.test.Log_slf4j_Test: warn msg
2022-04-09 12:41:18,476 ERROR [main] com.log.test.Log_slf4j_Test: error msg
结果同1.4
在logback实战中,我们说过,springboot-start-web中默认使用的是logback,所以如果我们要使用log4j2,还是要先排除logback相关依赖,如下
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-logging
org.springframework.boot
spring-boot-starter-log4j2
同1.2
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class Log4j2_slf4j_Test implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(Log4j2_slf4j_Test.class);
@Override
public void afterPropertiesSet() throws Exception {
logger.debug("debug msg");
logger.info("info msg");
logger.warn("warn msg");
logger.error("error msg");
}
}
启动ApplicationRunner即可验证
2022-04-09 12:24:02,345 DEBUG [main] com.example.log4j2springboot.log.Log4j2_slf4j_Test: debug msg
2022-04-09 12:24:02,345 INFO [main] com.example.log4j2springboot.log.Log4j2_slf4j_Test: info msg
2022-04-09 12:24:02,346 WARN [main] com.example.log4j2springboot.log.Log4j2_slf4j_Test: warn msg
2022-04-09 12:24:02,346 ERROR [main] com.example.log4j2springboot.log.Log4j2_slf4j_Test: error msg
log4j2作为性能最好的日志框架,主要是由于它的异步打印方式。当然本文主要偏实战,后续有机会我们再来聊聊log4j2的同步和异步日志