SpringBoot整合+logback日志配置
Posted 旧巷里的旧少年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合+logback日志配置相关的知识,希望对你有一定的参考价值。
本次演示的代码结构如下,基于maven,整合SpringBoot、Spring、Mybaits的SSM框架。同时测试logback日志框架的使用及配置。
1.创建maven工程,修改pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>yan.li</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<!-- 使用UTF-8编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 使用jdk1.8版本 -->
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--整合mybatis所需的jar -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--热启动:每自修改后, 程序自动启动spring Application上下文。 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- 阿里json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.创建com.liyan.model包,同时创建两个PO类
(1)User.java类
package com.liyan.model;
import java.io.Serializable;
/**
* 员工实体类
* <p>Title: User</p>
* @author Liyan
* @date 2018年1月11日 上午10:45:20
*/
public class User implements Serializable{
private static final long serialVersionUID = 1L;
/** 自增主键 */
private Integer id;
/** 员工工号 */
private String userId;
/** 员工姓名 */
private String userName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
(2)ResponseResult.java类
package com.liyan.model;
/**
* 返回值实体类
* <p>Title: ResponseResult</p>
* @author Liyan
* @date 2018年1月11日 下午5:23:41
*/
public class ResponseResult {
private Integer code;
private String msg;
private Object data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public ResponseResult(Integer code, String msg, Object data) {
super();
this.code = code;
this.msg = msg;
this.data = data;
}
}
3.在com.liyan.mapper包下创建UserMapper.java接口
package com.liyan.mapper;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import com.liyan.model.User;
//这里可以使用@Mapper注解,但是每个mapper都加注解比较麻烦,所以统一配置@MapperScan在扫描路径在application类中
//@Mapper //声明是一个Mapper,与springbootApplication中的@MapperScan二选一写上即可
@Repository
public interface UserMapper {
@Select("SELECT id, user_id userId, user_name userName FROM user_tab WHERE user_id = #{userId}")
@ResultType(User.class)
User selectUser(String userId);
}
4.在com.liyan.service包下创建UserService.java接口
package com.liyan.service;
import com.liyan.model.User;
public interface UserService {
/**
* 根据员工工号,查询员工
* <p>Title: selectUser</p>
* @author Liyan
* @date 2018年1月11日 上午10:50:34
* @param userId 员工工号
* @return List<User>
*/
public User selectUser(String userId);
}
5.在com.liyan.service.impl包下创建UserServiceImpl.java类
package com.liyan.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.liyan.mapper.UserMapper;
import com.liyan.model.User;
import com.liyan.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User selectUser(String userId) {
return userMapper.selectUser(userId);
}
}
6.在com.liyan.exception包下创建三个自定义异常相关的类
(1)ExceptionEnum.java类
package com.liyan.exception;
/**
* 异常枚举类
* <p>Title: ExceptionEnum</p>
* @author Liyan
* @date 2018年1月11日 下午3:54:48
*/
public enum ExceptionEnum {
ERROR_NOFOUND("无法找到相应的数据");
private String value;
public String getValue() {
return value;
}
ExceptionEnum(String value){
this.value = value;
}
public String toString() {
return value;
}
}
(2)NoFoundExcepiton.java类
package com.liyan.exception;
/**
* 自定义No Found异常
* <p>Title: NoFoundExcepiton</p>
* @author Liyan
* @date 2018年1月11日 下午3:36:13
*/
public class NoFoundExcepiton extends Exception {
private static final long serialVersionUID = -5955607821816077172L;
public NoFoundExcepiton(String errorInfo) {
super(errorInfo);
}
}
(3)GlobalExceptionHandler.java全局异常类
package com.liyan.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.liyan.model.ResponseResult;
@CrossOrigin
@RestControllerAdvice
public class GlobalExceptionHandler {
private static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler
public ResponseResult processException(Exception ex, HttpServletRequest request, HttpServletResponse response){
ex.printStackTrace();
if(ex instanceof MissingServletRequestParameterException){
return new ResponseResult(400, ex.getMessage(), null);
}
if(ex instanceof NoFoundExcepiton){
LOGGER.error("======="+ex.getMessage()+"=======");
return new ResponseResult(401, "无法找到相应数据!", null);
}
return new ResponseResult(500, ex.getMessage(), null);
}
}
7.在com.liyan.controller包下创建
(1)创建UserController.java类
package com.liyan.controller;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.liyan.exception.ExceptionEnum;
import com.liyan.exception.NoFoundExcepiton;
import com.liyan.model.User;
import com.liyan.service.UserService;
@RestController
@EnableAutoConfiguration
@ComponentScan(basePackages={"com.liyan.model"})//添加的注解
public class UserController {
@Autowired
private UserService userService;
/**
* 引入日志,注意都是"org.slf4j"包下
*/
private final static Logger logger = LoggerFactory.getLogger(UserController.class);
/**
* 根据员工工号,查询员工
* <p>Title: selectUser</p>
* @author Liyan
* @date 2018年1月11日 上午11:37:46
* @param userId 员工工号
* @param httpServletResponse
* @return User
* @throws Exception
*/
@RequestMapping(value = "selectUser/{userId}",method = RequestMethod.GET)
public User selectUser(@PathVariable String userId, HttpServletResponse httpServletResponse) throws Exception {
User user = userService.selectUser(userId);
logger.info("访问selectUser/{userId}接口,参数userId = " + "userId");
if (user == null) {
logger.error("根据员工工号,查询员工异常:e=" + ExceptionEnum.ERROR_NOFOUND.getValue());
throw new NoFoundExcepiton(ExceptionEnum.ERROR_NOFOUND.getValue());
}
return user;
}
}
(2)创建UserController.java启动类
package com.liyan.controller;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* 启动类
* <p>Title: SpringbootApplication</p>
* @author Liyan
* @date 2018年1月11日 上午11:36:48
*/
@SpringBootApplication(scanBasePackages = {"com.liyan"})
@MapperScan("com.liyan.mapper")
@EnableTransactionManagement//开启事务管理
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
8.配置文件相关
(1)application.properties
#============ 数据库配置#======================================
spring.datasource.url=jdbc:mysql://127.0.0.1:3306?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
#用户名和密码
spring.datasource.username=记得换成自己的
spring.datasource.password=记得换成自己的
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.database=记得换成自己的
#============ tomcat配置#====================================
server.port=80
#============ mybatis配置 ====================================
#起别名。可省略写mybatis的xml中的resultType的全路径
mybatis.type-aliases-package=com.liyan.model
#Mybatis扫描(配置xml模式使用)
mybatis.mapper-locations=classpath*:mapper/*.xml
#=========== 日志配置·简易(spring boot已经集成logback日志)=========
#controller层日志 WARN级别输出
#logging.level.com.liyan.controller=WARN
#mapper层 sql日志 DEBUG级别输出
#logging.level.com.liyan.mapper=DEBUG
#logging.file=logs/spring-boot-logging.log
#logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
#logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n
#打印运行时sql语句到控制台
#spring.jpa.show-sql=true
#==================== 日志配合·标准 ============================
logging.config=classpath:logback-boot.xml
(2)logback-boot.xml 日志配置文件(重点)
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,%i索引【从数字0开始递增】,,, -->
<!-- appender是configuration的子节点,是负责写日志的组件。 -->
<!-- ConsoleAppender:把日志输出到控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %p (%file:%line)- %m%n</pattern>
<!-- 控制台也要使用UTF-8,不要使用GBK,否则会中文乱码 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- RollingFileAppender:滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
<!-- 以下的大概意思是:1.先按日期存日志,日期变了,将前一天的日志文件名重命名为XXX%日期%索引,新的日志仍然是demo.log -->
<!-- 2.如果日期没有发生变化,但是当前日志的文件大小超过1KB时,对当前日志进行分割 重命名-->
<appender name="demolog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>log/demo.log</File>
<!-- rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。 -->
<!-- TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 -->
<!-- 文件名:log/demo.2017-12-05.0.log -->
<fileNamePattern>log/demo.%d.%i.log</fileNamePattern>
<!-- 每产生一个日志文件,该日志文件的保存期限为30天 -->
<maxHistory>30</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- maxFileSize:这是活动文件的大小,默认值是10MB,测试时可改成1KB看效果 -->
<maxFileSize>1KB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<!-- pattern节点,用来设置日志的输入格式 -->
<pattern>
%d %p (%file:%line)- %m%n
</pattern>
<!-- 记录日志的编码:此处设置字符集 - -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 控制台输出日志级别 -->
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<!-- 指定项目中某个包,当有日志操作行为时的日志记录级别 -->
<!-- com.liyan为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG -->
<!-- 级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE -->
<logger name="com.liyan" level="DEBUG">
<appender-ref ref="demolog" />
</logger>
</configuration>
9.创建数据库表结构,建表语句如下,数据自己随便加吧
CREATE TABLE `user_tab` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` VARCHAR(10) NOT NULL,
`user_name` VARCHAR(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`) USING BTREE
) ENGINE=INNODB DEFAULT CHARSET=utf8
10.启动
11.访问:http://localhost/selectUser/G353 (多刷新几次,看日志效果)如下:
demo.log一旦大于刚刚配置的1kb,立即会被分割成按日期命名的各个小日志。
以上是关于SpringBoot整合+logback日志配置的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot2.x整合slf4j+logback日志框架
SpringBoot2.x整合slf4j+logback日志框架
springboot整合logback集成elk实现日志的汇总分析统计和检索功能