为什么使用日志打印而不是使用System.out.println()?
System.out是一个io流 如果使用它打印大批量数据 会占用大量的资源
spring默认使用common-logging打印日志信息 如果我们想替换掉它 使用其他的日志工具 分为如下几步
1.排除项目对common-logging的依赖
1
2
3
4
5
6
7
8
9
10
|
< dependency > < groupId >org.springframework</ groupId > < artifactId >spring-orm</ artifactId > < exclusions > < exclusion > < groupId >commons-logging</ groupId > < artifactId >commons-logging</ artifactId > </ exclusion > </ exclusions > </ dependency > |
因为我所用的项目中common-logging在此依赖之下 所以需要将其排除
2.引入取代common-logging的日志打印工具的依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!--其他日志工具的中间转换包--> < dependency > < groupId >org.slf4j</ groupId > < artifactId >jcl-over-slf4j</ artifactId > </ dependency > < dependency > < groupId >org.slf4j</ groupId > < artifactId >slf4j-api</ artifactId > < version >1.7.7</ version > </ dependency > < dependency > < groupId >ch.qos.logback</ groupId > < artifactId >logback-classic</ artifactId > < version >1.2.3</ version > </ dependency > |
SLF4J对应不同框架如图所示
我这里引入的是转logback的依赖
3.配置logback.xml 设置输出的日志
先测试一下
结果如图 打印的日志太长了 设置打印的日志的格式和等级就需要logback.xml了
内容如图:(logback.xml在rescouce目录下)
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<? xml version = "1.0" encoding = "UTF-8" ?> < configuration debug = "true" > <!-- 指定日志输出的位置 --> < appender name = "STDOUT" class = "ch.qos.logback.core.ConsoleAppender" > < encoder > <!-- 日志输出的格式 --> <!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体 内容、换行 --> < pattern >[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</ pattern > </ encoder > </ appender > <!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR --> <!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 --> < root level = "INFO" > <!-- 指定打印日志的 appender,这里通过“STDOUT”引用了前面配置的 appender --> < appender-ref ref = "STDOUT" /> </ root > <!-- 根据特殊需求指定局部日志级别 --> < logger name = "com.atguigu.crowd.mapper" level = "DEBUG" /> </ configuration > |
设置后结果如图