java中常见日志框架:
日志实现 | |
---|---|
JCL(Apache Commons Logging) 、SLF4J(Sample Logging Facade For Java)、 jboss-logging | log4j、jul(java.util.logging) 、log4j2 、 |
实际开发中常用slf4j作为日志门面,实现接口已log4j、logback为主。slf4j官网:http://www.slf4j.org/index.html
下面介绍日志框架使用
1、jar包选用
下图为slf4j结合日志实现的使用方式:以纵向方式结合
场景:项目中使用不同的jar包,用的日志框架可能不一致,有的用commons-logging、有的用log4j、有的用logback。这时就会面临日志文件配置混乱的问题。针对此问题我们看看slf4j给出整合方案:
如果我们自己的项目用使用slf4j+logback,结合图上第一块区域。
1)对于commons-logging.jar我们jcl-over-slf4j.jar替换;对于log4j.jar我们用log4j-over-slf4j.jar替换;对于jdk的log我们用jul-to-slf4j.jar替换。
这些xx-slf4j.jar包属于适配层,假如spring底层用到commons-logging中的api时,此时就会调用到 jcl-over-slf4j.jar包中的api,通过
jcl-over-slf4j.jar包调用logback*.jar中的日志记录器记录日志。其实这些适配层的jar跟被替换的jar中都有相同类名、更方法名。
2)引入适配层的jar之后,为了避免冲突还应该删除原来应用的jar包:commons-logging.jar、log4j.jar等。maven项目排除依赖jar包配置如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>spring-jcl</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
3)日志文件配置中可配项跟使用原来的jar包一样配置即可。
3、springboot中日志文件名称
推荐日志文件名称如下,存放于classpath下(resources目下)
Logging System | Customization |
---|---|
Logback | logback-spring.xml , logback-spring.groovy , logback.xml , or logback.groovy |
Log4j2 | log4j2-spring.xml or log4j2.xml |
JDK (Java Util Logging) | logging.properties |
如果日志文件命名方式为xx-spring.xml方式,则可以使用profiles功能,切换不同的环境,当然application.yml中还需
配置spring-profiles-active属性。
<springProfile name="staging">
<!-- configuration to be enabled when the "staging" profile is active -->
</springProfile>
<springProfile name="dev | staging"><!--或者-->
<!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
</springProfile>
<springProfile name="!production"><!--非-->
<!-- configuration to be enabled when the "production" profile is not active -->
</springProfile>