日志-logback

Posted WwpwW

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了日志-logback相关的知识,希望对你有一定的参考价值。

终于有时间整理logback-spring.xml文件了,搭建完整的javaWeb项目也就缺少了这项基本技能了。不多介绍了,看下整个完整的项目项目搭建流程吧。


pom文件,所需要的jar包依赖项都在下面的文件里~

<?xml version="1.0" encoding="UTF-8"?><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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.wpw</groupId> <artifactId>logback</artifactId> <version>0.0.1-SNAPSHOT</version> <name>logback</name> <description>Demo project for Spring Boot</description>
<properties> <java.version>1.8</java.version> </properties>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </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>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> <scope>runtime</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>

基础类对象~user

package com.wpw.logback;
import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor;import lombok.experimental.Accessors;
import java.io.Serializable;
/** * @author pc */@Data@AllArgsConstructor@NoArgsConstructor@Builder@Accessors(chain = true)public class User implements Serializable { private static final long serialVersionUID = -4554017265134170577L; private Integer id; private String userId; private String userName;}

返回的结果类~Result

package com.wpw.logback;
import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor;import lombok.experimental.Accessors;
import java.io.Serializable;
/** * @author pc */@Data@Accessors(chain = true)@Builder@AllArgsConstructor@NoArgsConstructorpublic class Result<T> implements Serializable { private static final long serialVersionUID = -1842792104117722746L; private Integer code; private String message; private T data;
public static <T> Result<T> ofSuccess(Integer code, String message, T data) { Result<T> result = new Result<>(); return result.setCode(code).setMessage(message).setData(data); }
public static <T> Result<T> ofError(Integer code, String message, T data) { Result<T> result = new Result<>(); return result.setCode(code).setMessage(message).setData(data); }}

枚举类~ExceptionEnum

package com.wpw.logback;
import lombok.Data;
/** * @author pc */public enum ExceptionEnum {

NOT_FOUND( "对应的数据不存在");
private String value;
ExceptionEnum(String value) { this.value = value; }
public String getValue() { return value; }
@Override public String toString() { return "ExceptionEnum{" + "value='" + value + '\'' + '}'; }}

工具类~CheckUtil

package com.wpw.logback;
import org.springframework.util.StringUtils;
import java.util.Objects;
/** * @author pc */public class CheckUtil { public static void preCheck(Object o) throws MyException { if (Objects.isNull(o)) { throw new MyException("参数为空"); } }
public static void preCheckOfStr(String str) throws MyException { if (StringUtils.isEmpty(str)) { throw new MyException("字符串不能为空"); } }}

全局控制器~GlobalExceptionHandler

package com.wpw.logback;
import lombok.extern.slf4j.Slf4j;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 javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
/** * @author pc */@Slf4j@CrossOrigin@RestControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler public Result process(Exception e, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { if (e instanceof MissingServletRequestParameterException) { return Result.ofError(400, "缺少参数", null); } else if (e instanceof MyException) { return Result.ofError(401, ExceptionEnum.NOT_FOUND.getValue(), null); } else { return Result.ofError(500, "系统异常", null); }
}}

数据库配置文件~application.yaml

spring: application: name: logback datasource: driver-class-name: com.mysql.jdbc.Driver username: root password: 123456    url: jdbc:mysql://自己mysql服务器地址:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=trueserver: port: 8080mybatis: type-aliases-package: com.wpw.logbacklogging: config: classpath:logback-spring.xml

日志配置文件~logback-spring.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="logback-project" class="ch.qos.logback.core.rolling.RollingFileAppender"> <File>log/logback-project.log</File> <!-- rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。--> <!-- TimeBasedRollingPolicy:最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 --> <!-- 文件名:log/demo.2017-12-05.0.log --> <fileNamePattern>log/logback-project.%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.wpw.logback为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG --> <!-- 级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE --> <logger name="com.wpw.logback" level="DEBUG"> <appender-ref ref="logback-project"/> </logger></configuration>

自定义异常

package com.wpw.logback;
/** * @author pc */public class MyException extends Exception { public MyException(String message) { super(message); }}

开始测试我们的功能实现了。

a.controllerb.servicec.mapper

控制器Controller

package com.wpw.logback;
import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;import java.util.Objects;
/** * @author pc */@RestController@Slf4j@RequestMapping(value = "/user")public class UserController { private final UserService userService;
public UserController(UserService userService) { this.userService = userService; }
@GetMapping(value = "/get") public User getUser(@RequestParam(value = "userId") Integer userId) throws MyException { CheckUtil.preCheck(userId); User user = userService.getUser(userId); if (Objects.isNull(user)) { throw new MyException(ExceptionEnum.NOT_FOUND.getValue()); } return user; }}

业务逻辑处理service接口

package com.wpw.logback;
/** * @author pc */public interface UserService { /** * 根据userId获取用户信息 * * @param userId 用户id * @return user */ User getUser(Integer userId);}

业务逻辑处理service实现类

package com.wpw.logback;
import org.springframework.stereotype.Service;
import java.util.Optional;
/** * @author pc */@Servicepublic class UserServiceImpl implements UserService { private final UserMapper userMapper;
public UserServiceImpl(UserMapper userMapper) { this.userMapper = userMapper; }
@Override public User getUser(Integer userId) { return Optional.ofNullable(userMapper.getUser(userId)).orElse(null); }}

数据访问层-dao

package com.wpw.logback;
import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.ResultType;import org.apache.ibatis.annotations.Select;
/** * @author pc */@Mapperpublic interface UserMapper { /** * 根据userId获取用户信息 * * @param userId 用户id * @return user */ @Select(value = "select id id,user_id userId,user_name userName from user where user_id=#{userId}") @ResultType(User.class) User getUser(Integer userId);}

整个文章对logback的使用已经完成,喜欢文章的可以转发和关注。


以上是关于日志-logback的主要内容,如果未能解决你的问题,请参考以下文章

LogBack 没有打印日志

logback整合rabbit

logback工作原理研究

日志框架之Logback的使用与详细配置

logback怎么根据logger输出不同文件

logback异步输出日志深入分析