日志介绍和新日志框架Logback讲解
1.常用处理java的日志组件 slf4j,log4j,logback,common-logging 等
2、logback介绍:基于Log4j基础上大量改良,不能单独使用,推荐配合日志框架SLF4J来使用
logback当前分成三个模块:logback-core,logback-classic和logback-access;
logback-core是其它两个模块的基础模块
3、Logback的核心对象:
Logger:日志记录器
Appender:指定日志输出的目的地,目的地可以是控制台,文件
Layout:日志布局 格式化日志信息的输出
4、日志级别:DEBUG < INFO < WARN < ERROR
===========log4j示例===========
### 设置###
log4j.rootLogger = debug,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志到=D://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = D://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志到=D://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
===========logback============
4、Log4j日志转换为logback在线工具(支持log4j.properties转换为logback.xml,不支持 log4j.xml转换为logback.xml)
https://logback.qos.ch/translator/
SpringBoot2.x整合Logback配置实战
1、官网介绍:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-logging
当启动Springboot的时候控制台输出的日志解析
时间格式以及精度
日志级别:此处是INFO级别
进程ID
---是分隔符
线程名称
日志名称,该日志是哪个类进行输出的(类的全限定名)
日志信息
各个组件案例:https://logback.qos.ch/manual/index.html
默认情况下,Spring Boot将日志输出到控制台
整合Logback实战
创建 日志文件logback-spring.xml,官方推荐 -spring.xml结尾
默认加载加载配置顺序 logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
注释:配置文件中的格式个顺序
<configuration> 子节点
<appender></appender>
<logger></logger>
<root></root>(要加在最后)
------------------------------------------------------
在项目中新建配置文件如下:
内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="consoleApp" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</layout>
</appender>
<appender name="fileInfoApp" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
<encoder>
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</encoder>
<!-- 滚动策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 路径 -->
<fileNamePattern>app_log/log/app.info.%d.log</fileNamePattern>
</rollingPolicy>
</appender>
<appender name="fileErrorApp" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</encoder>
<!-- 设置滚动策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 路径 -->
<fileNamePattern>app_log/log/app.err.%d.log</fileNamePattern>
<!-- 控制保留的归档文件的最大数量,超出数量就删除旧文件,假设设置每个月滚动,
且<maxHistory> 是1,则只保存最近1个月的文件,删除之前的旧文件
-->
<MaxHistory>1</MaxHistory>
</rollingPolicy>
</appender>
<!-- 控制输出的级别 -->
<root level="INFO">
<appender-ref ref="consoleApp"/>
<appender-ref ref="fileInfoApp"/>
<appender-ref ref="fileErrorApp"/>
</root>
</configuration>
测试代码:
访问测试:启动SpringBoot,访问浏览器如下
控制台输出:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.1.RELEASE)
2020-01-10 10:25:18.155 INFO [restartedMain]net.xdclass.base_project.XdclassApplication.logStarting:55 -Starting XdclassApplication on LAPTOP-JLA8JBR3 with PID 35244 (E:\workspace\base_project\target\classes started by wq in E:\workspace\base_project)
2020-01-10 10:25:18.158 INFO [restartedMain]net.xdclass.base_project.XdclassApplication.logStartupProfileInfo:651 -No active profile set, falling back to default profiles: default
2020-01-10 10:25:18.220 INFO [restartedMain]o.s.b.devtools.env.DevToolsPropertyDefaultsPostProcessor.logTo:225 -Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-01-10 10:25:18.221 INFO [restartedMain]o.s.b.devtools.env.DevToolsPropertyDefaultsPostProcessor.logTo:225 -For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-01-10 10:25:18.885 INFO [restartedMain]o.s.d.repository.config.RepositoryConfigurationDelegate.multipleStoresDetected:246 -Multiple Spring Data modules found, entering strict repository configuration mode!
2020-01-10 10:25:18.888 INFO [restartedMain]o.s.d.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn:126 -Bootstrapping Spring Data repositories in DEFAULT mode.
2020-01-10 10:25:18.917 INFO [restartedMain]o.s.d.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn:184 -Finished Spring Data repository scanning in 15ms. Found 0 repository interfaces.
2020-01-10 10:25:19.350 INFO [restartedMain]o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization:330 -Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-01-10 10:25:20.168 INFO [restartedMain]o.s.boot.web.embedded.tomcat.TomcatWebServer.initialize:92 -Tomcat initialized with port(s): 8080 (http)
2020-01-10 10:25:20.246 INFO [restartedMain]org.apache.coyote.http11.Http11NioProtocol.log:173 -Initializing ProtocolHandler ["http-nio-8080"]
2020-01-10 10:25:20.246 INFO [restartedMain]org.apache.catalina.core.StandardService.log:173 -Starting service [Tomcat]
2020-01-10 10:25:20.247 INFO [restartedMain]org.apache.catalina.core.StandardEngine.log:173 -Starting Servlet engine: [Apache Tomcat/9.0.27]
2020-01-10 10:25:20.337 INFO [restartedMain]o.a.catalina.core.ContainerBase.[Tomcat].[localhost].[/].log:173 -Initializing Spring embedded WebApplicationContext
2020-01-10 10:25:20.338 INFO [restartedMain]org.springframework.web.context.ContextLoader.prepareWebApplicationContext:284 -Root WebApplicationContext: initialization completed in 2116 ms
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Property 'mapperLocations' was not specified.
2020-01-10 10:25:21.214 INFO [restartedMain]o.s.scheduling.concurrent.ThreadPoolTaskExecutor.initialize:171 -Initializing ExecutorService 'applicationTaskExecutor'
2020-01-10 10:25:21.517 INFO [restartedMain]o.s.scheduling.concurrent.ThreadPoolTaskScheduler.initialize:171 -Initializing ExecutorService 'taskScheduler'
2020-01-10 10:25:21.589 INFO [restartedMain]o.s.boot.devtools.autoconfigure.OptionalLiveReloadServer.startServer:58 -LiveReload server is running on port 35729
2020-01-10 10:25:21.664 INFO [restartedMain]org.apache.coyote.http11.Http11NioProtocol.log:173 -Starting ProtocolHandler ["http-nio-8080"]
2020-01-10 10:25:21.707 INFO [restartedMain]o.s.boot.web.embedded.tomcat.TomcatWebServer.start:204 -Tomcat started on port(s): 8080 (http) with context path ''
2020-01-10 10:25:21.710 INFO [restartedMain]net.xdclass.base_project.XdclassApplication.logStarted:61 -Started XdclassApplication in 3.944 seconds (JVM running for 4.441)
2020-01-10 10:25:59.440 INFO [http-nio-8080-exec-1]o.a.catalina.core.ContainerBase.[Tomcat].[localhost].[/].log:173 -Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-01-10 10:25:59.441 INFO [http-nio-8080-exec-1]org.springframework.web.servlet.DispatcherServlet.initServletBean:525 -Initializing Servlet 'dispatcherServlet'
2020-01-10 10:25:59.451 INFO [http-nio-8080-exec-1]org.springframework.web.servlet.DispatcherServlet.initServletBean:547 -Completed initialization in 10 ms
2020-01-10 10:25:59.474 INFO [http-nio-8080-exec-1]net.xdclass.base_project.controller.UserController.testLog:29 -this is info level
2020-01-10 10:25:59.475 WARN [http-nio-8080-exec-1]net.xdclass.base_project.controller.UserController.testLog:30 -this is warn level
2020-01-10 10:25:59.475 ERROR[http-nio-8080-exec-1]net.xdclass.base_project.controller.UserController.testLog:31 -this is error level
日志文件生成如下:
将日志在控制台输出同时将INFO和WARN信息写入文件,将ERROR信息也写入文件,项目中会生成一个新的文件夹app_log,含有子文件夹log,新生成的日志文件在该目录下,INFO级别的文件名为app.info.2020-01-10.log,ERROR级别的文件名为app.err.2020-01-10.log,上图中可见
err日志内容如下:
2020-01-10 10:25:59.475 ERROR[http-nio-8080-exec-1]net.xdclass.base_project.controller.UserController.testLog:31 -this is error level
info日志内容如下:
2020-01-10 10:25:18.155 INFO [restartedMain]net.xdclass.base_project.XdclassApplication.logStarting:55 -Starting XdclassApplication on LAPTOP-JLA8JBR3 with PID 35244 (E:\workspace\base_project\target\classes started by wq in E:\workspace\base_project)
2020-01-10 10:25:18.158 INFO [restartedMain]net.xdclass.base_project.XdclassApplication.logStartupProfileInfo:651 -No active profile set, falling back to default profiles: default
2020-01-10 10:25:18.220 INFO [restartedMain]o.s.b.devtools.env.DevToolsPropertyDefaultsPostProcessor.logTo:225 -Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-01-10 10:25:18.221 INFO [restartedMain]o.s.b.devtools.env.DevToolsPropertyDefaultsPostProcessor.logTo:225 -For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-01-10 10:25:18.885 INFO [restartedMain]o.s.d.repository.config.RepositoryConfigurationDelegate.multipleStoresDetected:246 -Multiple Spring Data modules found, entering strict repository configuration mode!
2020-01-10 10:25:18.888 INFO [restartedMain]o.s.d.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn:126 -Bootstrapping Spring Data repositories in DEFAULT mode.
2020-01-10 10:25:18.917 INFO [restartedMain]o.s.d.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn:184 -Finished Spring Data repository scanning in 15ms. Found 0 repository interfaces.
2020-01-10 10:25:19.350 INFO [restartedMain]o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization:330 -Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-01-10 10:25:20.168 INFO [restartedMain]o.s.boot.web.embedded.tomcat.TomcatWebServer.initialize:92 -Tomcat initialized with port(s): 8080 (http)
2020-01-10 10:25:20.246 INFO [restartedMain]org.apache.coyote.http11.Http11NioProtocol.log:173 -Initializing ProtocolHandler ["http-nio-8080"]
2020-01-10 10:25:20.246 INFO [restartedMain]org.apache.catalina.core.StandardService.log:173 -Starting service [Tomcat]
2020-01-10 10:25:20.247 INFO [restartedMain]org.apache.catalina.core.StandardEngine.log:173 -Starting Servlet engine: [Apache Tomcat/9.0.27]
2020-01-10 10:25:20.337 INFO [restartedMain]o.a.catalina.core.ContainerBase.[Tomcat].[localhost].[/].log:173 -Initializing Spring embedded WebApplicationContext
2020-01-10 10:25:20.338 INFO [restartedMain]org.springframework.web.context.ContextLoader.prepareWebApplicationContext:284 -Root WebApplicationContext: initialization completed in 2116 ms
2020-01-10 10:25:21.214 INFO [restartedMain]o.s.scheduling.concurrent.ThreadPoolTaskExecutor.initialize:171 -Initializing ExecutorService 'applicationTaskExecutor'
2020-01-10 10:25:21.517 INFO [restartedMain]o.s.scheduling.concurrent.ThreadPoolTaskScheduler.initialize:171 -Initializing ExecutorService 'taskScheduler'
2020-01-10 10:25:21.589 INFO [restartedMain]o.s.boot.devtools.autoconfigure.OptionalLiveReloadServer.startServer:58 -LiveReload server is running on port 35729
2020-01-10 10:25:21.664 INFO [restartedMain]org.apache.coyote.http11.Http11NioProtocol.log:173 -Starting ProtocolHandler ["http-nio-8080"]
2020-01-10 10:25:21.707 INFO [restartedMain]o.s.boot.web.embedded.tomcat.TomcatWebServer.start:204 -Tomcat started on port(s): 8080 (http) with context path ''
2020-01-10 10:25:21.710 INFO [restartedMain]net.xdclass.base_project.XdclassApplication.logStarted:61 -Started XdclassApplication in 3.944 seconds (JVM running for 4.441)
2020-01-10 10:25:59.440 INFO [http-nio-8080-exec-1]o.a.catalina.core.ContainerBase.[Tomcat].[localhost].[/].log:173 -Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-01-10 10:25:59.441 INFO [http-nio-8080-exec-1]org.springframework.web.servlet.DispatcherServlet.initServletBean:525 -Initializing Servlet 'dispatcherServlet'
2020-01-10 10:25:59.451 INFO [http-nio-8080-exec-1]org.springframework.web.servlet.DispatcherServlet.initServletBean:547 -Completed initialization in 10 ms
2020-01-10 10:25:59.474 INFO [http-nio-8080-exec-1]net.xdclass.base_project.controller.UserController.testLog:29 -this is info level
2020-01-10 10:25:59.475 WARN [http-nio-8080-exec-1]net.xdclass.base_project.controller.UserController.testLog:30 -this is warn level
日志中配置了error级别信息的记录、info和warn日志的记录,没有debug的日志记录(控制台有)
--------------------------------------