1、依赖
<!-- spring boot start -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<!-- 排除自带的logback依赖 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- springboot-log4j -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
2、Log4j配置文件(建立在和application文件同级的目录下)
# Log4j配置
log4j.rootCategory=INFO,stdout
#控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
注:该文件里的stdout全部替换成CONSOLE也是没有问题的。当然你也可以在文件中配置file,error,debug等其他的日志信息。
3、使用Log4j
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author EchoDemo
* @ClassName cn.aduu.web.HelloController
* @Description
*/
@RestController
public class HelloController{
private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
@RequestMapping("hello")
public String hello() throws JsonProcessingException {
logger.info("Hello World!");
return "hello world";
}
}
注:启动之后在浏览器访问就好了。
4、日志打印效果
十一月 20, 2018 10:42:10 下午 org.apache.catalina.core.ApplicationContext log
2018-11-20-22-42 [http-nio-8080-exec-1] [org.springframework.web.servlet.DispatcherServlet] [INFO] - FrameworkServlet 'dispatcherServlet': initialization started
信息: Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-11-20-22-42 [http-nio-8080-exec-1] [org.springframework.web.servlet.DispatcherServlet] [INFO] - FrameworkServlet 'dispatcherServlet': initialization completed in 23 ms
2018-11-20-22-42 [http-nio-8080-exec-1] [com.echodemo.girl.web.UserController] [INFO] - Hello World!