slf4j是对全部日志框架制定的一种规范、标准、接口,并非一个框架的具体的实现,由于接口并不能独立使用,须要和具体的日志框架实现配合使用(如log4j、logback),使用接口的好处是当项目须要更换日志框架的时候,只须要更换jar和配置,不须要更改相关java代码java
log4j、logback、log4j2都是一种日志具体实现框架,因此既能够单独使用也能够结合slf4j一块儿搭配使用web
springboot项目中需导入:spring
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>apache
如项目中有导入spring-boot-starter-web依赖包记得去掉spring自带的日志依赖spring-boot-starter-logging,以下:json
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>springboot
springboot方式:
application.properties中添加配置 logging.config=classpath:log4j2_dev.xml, log4j2_dev.xml是你建立的log4j2的配置文件名,放在resources下,如放在其余路径则对应修改app
Web工程方式:框架
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>/WEB-INF/conf/log4j2.xml</param-value>
</context-param>
<listener>
<listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>异步
纯Java方式:
public static void main(String[] args) throws IOException {
File file = new File("D:/log4j2.xml");
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
final ConfigurationSource source = new ConfigurationSource(in);
Configurator.initialize(null, source);
Logger logger = LogManager.getLogger("myLogger");
}spring-boot
配置文件的格式:log2j配置文件能够是xml格式的,也能够是json格式的, 配置文件的位置:log4j2默认会在classpath目录下寻找log4j2.xml、log4j.json、log4j.jsn等名称的文件,若是都没有找到,则会按默认配置输出,也就是输出到控制台,也能够对配置文件自定义位置(须要在web.xml中配置),通常放置在src/main/resources根目录下便可