日志框架是任何一套系统中不可获取的部分,我们需要通过日志来记录用户的有效操作。
JUL: JDK 自带的Logging(实现太过简陋,对开发者不友好)
JCL: Jakarta Commons Loggin(Apache)()
Log4j:(作者是ceki,Log4j是作者选择放弃而推荐Logback)
Log4j2:(Apache,过于先进,开源框架对其支持有限,最大的优势是高于Log4j的超高性能)
Logback:(作者是ceki,真正意义上的Log4j2)
SLF4j:(作者是ceki,
jboss-logging:(诞生之初就不是为了服务大众,也没有收到青睐)
简单的日志示例
一个简单的日志示例:
import org.slf4j.Logger; @RunWith(SpringRunner.class) // 指定上下文,让日志运行于Spring环境 @SpringBootTest public class LoggerTest { private final Logger logger = LoggerFactory.getLogger(LoggerTest.class); @Test public void test1() { logger.debug("debug..."); logger.info("info..."); logger.error("error..."); } }
输出结果:
之所以没有打印debug的内容是因为系统默认打印info以上的内容,那么系统有哪些层级呢?
查看系统的层级
ctrl + N (windows) 查找类:
从上面的代码我们可以看到我们需要用到LoggerFactory.getLogger(类名),才能让输出的时候打印出本类的类名。这样每次都要配置就非常麻烦,那么我们可以借助一个小插件,来优化这个过程。
lombok插件 —— 这个插件不仅可以帮我们简化getter,setter方法的编写,还能帮我们减少很多代码的编写,也能帮助我们优化日志的使用,具体安装及配置见如下连接:lombok在idea中安装以及使用
利用lombok优化后,代码如下:
@RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class LoggerTest { @Test public void test1() { String name = "imooc"; String password = "123456"; log.debug("debug..."); log.info("info..."); log.info("name: {}, password: {}", name, password); log.error("error..."); } }
运行结果如下:
Logback的配置
通过修改Logback的配置,可以个性化完成我们的日志需求,也能实现上面讲过的各种功能。
配置的Logback的文件
appilcation.yml (配置简单,功能简单)
logback-spring.xml (配置复杂,功能强大)
假设我们有以下两个需求:
区分info和error日志
每天产生一个日志文件
具体配置过程
配置application.yml
logging: pattern: # console: "%d - %msg%n" # 指定控制到输出格式,但日志文件可以看到详细信息 # path: /var/log/tomcat/ # 指定输出路径 file: /var/log/tomcat/sell.log #指定输出文件 level: debug #指定日志级别 level: com.dante.imooc.sell.LoggerTest: debug #指定某一类的日志级别
application.yml只能简单的配置一些指定路径,如果我们需要完成更复杂的目标,就需要更详细的配置。
配置logback-spring.xml指定不同level的日志到不同的文件,并且按时间滚动。
1.resources目录下新建logback-spring.xml文件
2.进行日志输出配置,配置示例如下:
<?xml version="1.0" encoding="UTF-8" ?> <configuration> <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender"> <Layout class="ch.qos.logback.classic.PatternLayout"> <pattern> %d - %msg%n </pattern> </Layout> </appender> <appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <!--禁止--> <onMatch>DENY</onMatch> <!--接受--> <onMismatch>ACCEPT</onMismatch> <!--命中ERROR就DENY,没有命中ERROR就ACCEPT--> <!--filter三种操作,DENY(禁止),NEUTRAL(中立),ACCEPT(接受): 分别对应拒绝,忽略,接受--> </filter> <encoder> <pattern> %msg%n </pattern> </encoder> <!--滚动策略--> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--路径--> <fileNamePattern>/var/log/tomcat/sell/info.%d.log</fileNamePattern> </rollingPolicy> </appender> <appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>ERROR</level> </filter> <encoder> </encoder> <!--滚动策略--> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--路径--> <fileNamePattern>/var/log/tomcat/sell/error.%d.log</fileNamePattern> </rollingPolicy> </appender> <root level="info"> <appender-ref ref="consoleLog"/> <appender-ref ref="fileInfoLog"/> <appender-ref ref="fileErrorLog"/> </root> </configuration>
3.关于配置的细节可以参照依赖库“org.springframework.boot.logging.logback”的下列文件:
base.xml <?xml version="1.0" encoding="UTF-8"?> <!-- Base logback configuration provided for compatibility with Spring Boot 1.1 --> <included> <include resource="org/springframework/boot/logging/logback/defaults.xml" /> <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/> <include resource="org/springframework/boot/logging/logback/console-appender.xml" /> <include resource="org/springframework/boot/logging/logback/file-appender.xml" /> <root level="INFO"> <appender-ref ref="CONSOLE" /> <appender-ref ref="FILE" /> </root> </included>
defaults.xml <?xml version="1.0" encoding="UTF-8"?> <!-- Default logback configuration provided for import, equivalent to the programmatic initialization performed by Boot --> <included> <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" /> <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" /> <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" /> <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/> <property name="FILE_LOG_PATTERN" value="${FILE_LOG_PATTERN:-%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/> <appender name="DEBUG_LEVEL_REMAPPER" class="org.springframework.boot.logging.logback.LevelRemappingAppender"> <destinationLogger>org.springframework.boot</destinationLogger> </appender> <logger name="org.apache.catalina.startup.DigesterFactory" level="ERROR"/> <logger name="org.apache.catalina.util.LifecycleBase" level="ERROR"/> <logger name="org.apache.coyote.http11.Http11NioProtocol" level="WARN"/> <logger name="org.apache.sshd.common.util.SecurityUtils" level="WARN"/> <logger name="org.apache.tomcat.util.net.NioSelectorPool" level="WARN"/> <logger name="org.crsh.plugin" level="WARN"/> <logger name="org.crsh.ssh" level="WARN"/> <logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="ERROR"/> <logger name="org.hibernate.validator.internal.util.Version" level="WARN"/> <logger name="org.springframework.boot.actuate.autoconfigure.CrshAutoConfiguration" level="WARN"/> <logger name="org.springframework.boot.actuate.endpoint.jmx" additivity="false"> <appender-ref ref="DEBUG_LEVEL_REMAPPER"/> </logger> <logger name="org.thymeleaf" additivity="false"> <appender-ref ref="DEBUG_LEVEL_REMAPPER"/> </logger> </included>
file-appender.xml <?xml version="1.0" encoding="UTF-8"?> <!-- File appender logback configuration provided for import, equivalent to the programmatic initialization performed by Boot --> <included> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> </encoder> <file>${LOG_FILE}</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>${LOG_FILE}.%i</fileNamePattern> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> </included>
console-appender.xml <?xml version="1.0" encoding="UTF-8"?> <!-- Console appender logback configuration provided for import, equivalent to the programmatic initialization performed by Boot --> <included> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>${CONSOLE_LOG_PATTERN}</pattern> <charset>utf8</charset> </encoder> </appender> </included>
<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">
原文地址:https://www.cnblogs.com/DDante/p/1ced379dfab8addd01470a79b99941ff.html