Java日志框架众多,常用的有java.util.logging, log4j, logback,commons-logging等等。个人比较偏好的是slf4j,同时也比较偏好使用后缀为.properties作为日志的配置文件,可能是因为比较熟悉这个吧,下面就来分享一下SpringBoot中集成日志的经验。日志记录器(Logger)是日志处理的核心组件,日志常用的有五个级别,有低到高依次为debug(调试 ),info(消息),warn(警告),error(错误),fatal(严重错误)。通常可以根据实际所需要的颗粒度的大小选择其中的几个。我们公司当前用的就是debug,info,warn,error4个级别。废话不多说,开始操作。
idea+jdk1.8
这里我就不多说了,按照步骤来吧!!!
步骤1:
步骤2:
步骤3:
步骤4:
步骤5:
自此,一个maven项目创建完毕
4.0.0
spring-boot
spring-boot01
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
1.5.13.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-logging
org.slf4j
slf4j-api
1.7.21
org.slf4j
slf4j-log4j12
1.7.21
commons-logging
commons-logging
1.2
org.springframework.boot
spring-boot-maven-plugin
###创建MyApplication启动类
说明:
1.不要直接在java目录下直接创建类,要新建一个package
2.类名可以随便取,但是要遵循命名规范
package com.controller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Created by Administrator on 2018/5/20 0020.
*/
@SpringBootApplication
public class MyApplication {
public static void main(String[] args){
SpringApplication.run(MyApplication.class, args);
}
}
说明:@SpringBootApplication相当于添加@Configuration,@EnableAutoConfiguration,@ComponentScan三个注解
###创建控制器TestController类
说明:
1.这个TestController类要和MyApplication类同级或者在其同级的子目录下,否者在访问接口时会出现404
2.如果不想让TestController在MyApplication类同级或者在其同级的子目录下则需要另行指定
package com.controller;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Administrator on 2018/5/20 0020.
*/
@RestController
@RequestMapping("/hello")
public class TestController {
private Logger logger = Logger.getLogger(TestController.class);
@RequestMapping("/hello")
public @ResponseBody String HelloWorld(){
for(int i=0;i<1000;i++){
logger.debug("debug"+i);
logger.info("info"+i);
logger.warn("warn"+i);
logger.error("error"+i);
logger.fatal("fatal"+i);
}
return "Hello World!";
}
}
###创建log4j.properties文件
在resources目录下创建log4j.properties文件并添加配置
###配置日志根Logger
log4j.rootLogger=DEBUG,stdout,file
#ERROR 为严重错误 主要是程序的错误
#WARN 为一般警告,比如session丢失
#INFO 为一般要显示的信息,比如登录登出
#DEBUG 为程序的调试信息
log4j.additivity.org.apache=true
###配置日志信息输出目的地Appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#org.apache.log4j.ConsoleAppender(控制台)
#org.apache.log4j.FileAppender(文件)
#org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件)
#org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件)
#org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
#log4j.appender.error.Target=System.out
###输出ERROR级别以上的日志
log4j.appender.stdout.threshold=INFO
###配置日志信息的格式(布局)
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#org.apache.log4j.HTMLLayout(以HTML表格形式布局)
#org.apache.log4j.PatternLayout(可以灵活地指定布局模式)
#org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串)
#org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)
###配置日志打印的格式格式化日志信息
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
#%m 输出代码中指定的消息
#%p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL
#%r 输出自应用启动到输出该log信息耗费的毫秒数
#%c 输出所属的类目,通常就是所在类的全名
#%t 输出产生该日志事件的线程名
#%n 输出一个回车换行符,Windows平台为“\r\n”,Unix平台为“\n”
#%d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss , SSS}
#%l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数
#log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH-mm
# '.'yyyy-MM:每月
# '.'yyyy-ww:每周
# '.'yyyy-MM-dd:每天
# '.'yyyy-MM-dd-a:每天两次
# '.'yyyy-MM-dd-HH:每小时
# '.'yyyy-MM-dd-HH-mm:每分钟
#log4j.appender.file.MaxFileSize=1MB
###滚动文件的最大数
#log4j.appender.file.MaxBackupIndex=8
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%-5p](%-30c{1}) [TxId : %X{PtxId} , SpanId : %X{PspanId}] [ET:%X{ENV_TYPE},AN:%X{APP_NAME},SN:%X{SERVICE_NAME},CN:%X{CONTAINER_NAME},CI:%X{CONTAINER_IP}] %m%n
log4j.appender.file.Threshold=DEBUG
###将消息增加到指定文件中,false指将消息覆盖指定的文件内容
log4j.appender.file.append=true
###日志的保存位置
#log4j.appender.file.File=E:/logs/file-debug-log.log
log4j.appender.file.File=E:/logs/debug-debug.log
###每天产生一个日志文件
#log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.maxFileSize=100
#log4j.appender.file.maxBackupIndex=5
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%-5p](%-30c{1}) [TxId : %X{PtxId} , SpanId : %X{PspanId}] [ET:%X{ENV_TYPE},AN:%X{APP_NAME},SN:%X{SERVICE_NAME},CN:%X{CONTAINER_NAME},CI:%X{CONTAINER_IP}] %m%n
#log4j.appender.file.Threshold=DEBUG
#log4j.appender.file.append=true
#log4j.appender.file.File=E:/logs/debug-log.log
###修改Tomcat容器的启动端口
在resources目录下创建application.properties文件,并添加端口配置server.port=9999,这个端口可以根据你的需要写
说明:
1.通常resources目录作为SpringBoot的默认的配置目录,如果不是这个目录则需要指定
2.通常SpringBoot使用的是内置的Tomcat容器,默认的端口是8080,也可以直接使用默认的配置
###启动测试
1.启动项目:在MyApplication.java类中运行mian方法
2.检查日志
"C:\Program Files\Java\jdk1.8.0_131\bin\java" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.3\lib\idea_rt.jar=53932:C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_131\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar;E:\workspace\SpringBoot01\target\classes;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-starter-web\1.5.13.RELEASE\spring-boot-starter-web-1.5.13.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\1.5.13.RELEASE\spring-boot-starter-tomcat-1.5.13.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\8.5.31\tomcat-embed-core-8.5.31.jar;C:\Users\Administrator\.m2\repository\org\apache\tomcat\tomcat-annotations-api\8.5.31\tomcat-annotations-api-8.5.31.jar;C:\Users\Administrator\.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\8.5.31\tomcat-embed-el-8.5.31.jar;C:\Users\Administrator\.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.31\tomcat-embed-websocket-8.5.31.jar;C:\Users\Administrator\.m2\repository\org\hibernate\hibernate-validator\5.3.6.Final\hibernate-validator-5.3.6.Final.jar;C:\Users\Administrator\.m2\repository\javax\validation\validation-api\1.1.0.Final\validation-api-1.1.0.Final.jar;C:\Users\Administrator\.m2\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;C:\Users\Administrator\.m2\repository\com\fasterxml\classmate\1.3.4\classmate-1.3.4.jar;C:\Users\Administrator\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.8.11.1\jackson-databind-2.8.11.1.jar;C:\Users\Administrator\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.8.0\jackson-annotations-2.8.0.jar;C:\Users\Administrator\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.8.11\jackson-core-2.8.11.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-web\4.3.17.RELEASE\spring-web-4.3.17.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-aop\4.3.17.RELEASE\spring-aop-4.3.17.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-beans\4.3.17.RELEASE\spring-beans-4.3.17.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-context\4.3.17.RELEASE\spring-context-4.3.17.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-webmvc\4.3.17.RELEASE\spring-webmvc-4.3.17.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-expression\4.3.17.RELEASE\spring-expression-4.3.17.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-core\4.3.17.RELEASE\spring-core-4.3.17.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-starter\1.5.13.RELEASE\spring-boot-starter-1.5.13.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot\1.5.13.RELEASE\spring-boot-1.5.13.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\1.5.13.RELEASE\spring-boot-autoconfigure-1.5.13.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\yaml\snakeyaml\1.17\snakeyaml-1.17.jar;C:\Users\Administrator\.m2\repository\org\slf4j\slf4j-api\1.7.21\slf4j-api-1.7.21.jar;C:\Users\Administrator\.m2\repository\org\slf4j\slf4j-log4j12\1.7.21\slf4j-log4j12-1.7.21.jar;C:\Users\Administrator\.m2\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar;C:\Users\Administrator\.m2\repository\commons-logging\commons-logging\1.2\commons-logging-1.2.jar" com.controller.MyApplication
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.13.RELEASE)
2018-05-22 00:49:14 INFO MyApplication:48 - Starting MyApplication on PC-20180507AMKP with PID 4764 (E:\workspace\SpringBoot01\target\classes started by Administrator in E:\workspace\SpringBoot01)
2018-05-22 00:49:14 INFO MyApplication:593 - No active profile set, falling back to default profiles: default
2018-05-22 00:49:14 INFO AnnotationConfigEmbeddedWebApplicationContext:583 - Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@67205a84: startup date [Tue May 22 00:49:14 CST 2018]; root of context hierarchy
2018-05-22 00:49:15 INFO Version:30 - HV000001: Hibernate Validator 5.3.6.Final
2018-05-22 00:49:15 INFO TomcatEmbeddedServletContainer:92 - Tomcat initialized with port(s): 9999 (http)
五月 22, 2018 12:49:15 上午 org.apache.catalina.core.StandardService startInternal
信息: Starting service [Tomcat]
五月 22, 2018 12:49:15 上午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/8.5.31
五月 22, 2018 12:49:15 上午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring embedded WebApplicationContext
2018-05-22 00:49:15 INFO ContextLoader:276 - Root WebApplicationContext: initialization completed in 984 ms
2018-05-22 00:49:16 INFO ServletRegistrationBean:190 - Mapping servlet: 'dispatcherServlet' to [/]
2018-05-22 00:49:16 INFO FilterRegistrationBean:258 - Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-22 00:49:16 INFO FilterRegistrationBean:258 - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-22 00:49:16 INFO FilterRegistrationBean:258 - Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-22 00:49:16 INFO FilterRegistrationBean:258 - Mapping filter: 'requestContextFilter' to: [/*]
2018-05-22 00:49:16 INFO RequestMappingHandlerAdapter:534 - Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@67205a84: startup date [Tue May 22 00:49:14 CST 2018]; root of context hierarchy
2018-05-22 00:49:16 INFO RequestMappingHandlerMapping:543 - Mapped "{[/hello/hello]}" onto public java.lang.String com.controller.TestController.HelloWorld()
2018-05-22 00:49:16 INFO RequestMappingHandlerMapping:543 - Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-05-22 00:49:16 INFO RequestMappingHandlerMapping:543 - Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-05-22 00:49:16 INFO SimpleUrlHandlerMapping:362 - Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-22 00:49:16 INFO SimpleUrlHandlerMapping:362 - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-22 00:49:16 INFO SimpleUrlHandlerMapping:362 - Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-22 00:49:16 INFO AnnotationMBeanExporter:431 - Registering beans for JMX exposure on startup
2018-05-22 00:49:16 INFO TomcatEmbeddedServletContainer:216 - Tomcat started on port(s): 9999 (http)
2018-05-22 00:49:16 INFO MyApplication:57 - Started MyApplication in 1.598 seconds (JVM running for 1.885)
2018-05-22 00:51:43 INFO DispatcherServlet:489 - FrameworkServlet 'dispatcherServlet': initialization started
五月 22, 2018 12:51:43 上午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-05-22 00:51:43 INFO DispatcherServlet:508 - FrameworkServlet 'dispatcherServlet': initialization completed in 9 ms
2018-05-22 00:51:43 INFO TestController:23 - info0
2018-05-22 00:51:43 WARN TestController:24 - warn0
2018-05-22 00:51:43 ERROR TestController:25 - error0
2018-05-22 00:51:43 FATAL TestController:26 - fatal0
2018-05-22 00:51:43 INFO TestController:23 - info1
2018-05-22 00:51:43 WARN TestController:24 - warn1
2018-05-22 00:51:43 ERROR TestController:25 - error1
2018-05-22 00:51:43 FATAL TestController:26 - fatal1
说明:控制台中的日志会记录一些配置,如果有问题可以看分析一下日志
(1).v1.5.13.RELEASE》》》 体现的是SpringBoot的版本
(2).Mapped “{[/hello/hello]}” onto public java.lang.String com.controller.TestController.HelloWorld()》》》体现的是接口的映射关系
(3).Tomcat started on port(s): 9999 (http)》》》体现的是内置Tomcat的启动端口
3.通过浏览器访问接口
http://localhost:9999/hello/hello
4.查看文件夹中的日志
以上是SpringBoot中引入slf4j日志管理工具的Demo,其实即使不引入slf4j基本配置内容SpringBoot也有自带的日志管理日志工具(logback),包括默认的基本配置内容,这个下次在说吧。因作者水平有限,难免会有疏忽和错误,读者可以参考一些官方文档,如下:
Slf4j官网
Log4j官网
SpingBoot官方指南
SpringBoot官网
喜欢多线程高并发的朋友可以关注下微信公众号multi-thread