Spring Boot 日志配置

看这里,Spring Boot-日志配置(超详细),足够详细清楚。

本文只是在看完后的简单汇总梳理,请查看原文


一、默认Logback

  1. 默认情况:Spring Boot使用Logback,INFO级别输出到控制台;
  2. 按说需要添加spring-boot-starter-logging依赖,实际无需添加,因为spring-boot-starter中已包含;
  3. 日志级别:TRACE < DEBUG < INFO < WARN < ERROR < FATAL

二、配置application.properties以应对简单场景

# 日志路径
logging.path=log/
# 日志文件(注意和logging.path同时配置的话,只有logging.file起作用)
logging.file=log/boot.log
logging.file.max-history=30(单位是天,默认7天)
logging.file.max-size=100MB(单位是KB、MB等,默认10MB)
# 日志级别(可具体到包)
logging.level.root=info
logging.level.com.fukaiit=DEBUG
# 日志格式
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

注意:
logging.path和logging.file已过时,新版使用logging.file.name和logging.file.path(不能同时生效):

logging.file.name=log/myapp.log   # 指定路径和文件名(用这个就够了)
logging.file.path=log/  # 只能指定路径,文件名默认spring.log

日志格式说明

%d{HH: mm:ss.SSS}——日志输出时间
%thread——输出日志的进程名字,这在Web应用以及异步任务处理中很有用
%-5level——日志级别,并且使用5个字符靠左对齐
%logger{36}——日志输出者的名字
%msg——日志消息
%n——平台的换行符

三、配置logback-spring.xml以应对复杂场景

在resources目录下配置logback-spring.xml即可被正确识别;指定自定义文件的方法:

logging.config=classpath:logging-config.xml

在涉及多环境配置的情况下不能使用logback.xml,因为logback.xml加载早于application.yml,需使用logback-spring.xml或自定义文件名实现日志配置。
在这里插入图片描述

一个较完整的例子,具体节点说明请参考这里

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- 定义变量 -->
    <property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n" />
	<!-- 定义从配置文件获取的变量 -->
	<springProperty scope="context" name="LOG_PATH" source="log.path" />

	<!-- 控制台输出 -->
	<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>${PATTERN}</pattern>
		</encoder>
	</appender>

	<!-- 开发环境 -->
	<springProfile name="dev">
		<logger name="com.light.springboot" level="debug" />
		<root level="info">
			<appender-ref ref="CONSOLE" />
		</root>
	</springProfile>

	<!-- 测试环境、生产环境 -->
	<springProfile name="test,prod">
		<!-- 文件输出-->
		<appender name="FILE-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
			<file>${LOG_PATH}/test123.log</file>
			<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
				<!-- 文件名称 -->
				<fileNamePattern>${LOG_PATH}/log/test123.%d{yyyy-MM-dd}.log</fileNamePattern>
				<!-- 文件最大保存历史数量 -->
				<MaxHistory>30</MaxHistory>
			</rollingPolicy>
			<layout class="ch.qos.logback.classic.PatternLayout">
				<pattern>${PATTERN}</pattern>
			</layout>
		</appender>
		<root level="info">
			<appender-ref ref="CONSOLE" />
			<appender-ref ref="FILE-OUT" />
		</root>
	</springProfile>

	<logger name="org.springframework.jdbc.core.JdbcTemplate" level="debug" />
	<logger name="org.apache.ibatis" level="debug"></logger>
</configuration>

四、打印日志logger.info()

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
public class DispatchController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@RequestMapping("/{template}.html")
	public String template(@PathVariable String template) {
		logger.info("fdsafsadfasdfas");
		return template;
	}
}

references:
Spring Boot-日志配置(超详细)
Spring Boot系列——日志配置

五、Spring Boot + AOP 统一处理日志

  1. 添加依赖
<!-- aop -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  1. 创建WebLogAspect
package com.fukaiit.aspect;

import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class WebLogAspect {
	private Logger logger = LoggerFactory.getLogger(getClass());

	// 记录请求处理时间
	ThreadLocal<Long> startTime = new ThreadLocal<Long>();

	@Pointcut("execution(public * com.fukaiit.controller..*.*(..))")
	public void webLog() {

	}

	@Before("webLog()")
	public void doBefore(JoinPoint joinPoint) {
		startTime.set(System.currentTimeMillis());

		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		logger.info("===============请求内容===============");
		logger.info("地址:" + request.getRequestURL().toString());
		logger.info("方式:" + request.getMethod());
		logger.info("方法:" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
		logger.info("参数:");
		Enumeration<String> enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String name = (String) enu.nextElement();
			logger.info("  {}:{}", name, request.getParameter(name));
		}
		logger.info("===============请求内容===============");
	}

	@AfterReturning(returning = "ret", pointcut = "webLog()")
	public void doAfterReturning(Object ret) throws Throwable {
		logger.info("---------------返回内容---------------");
		logger.info("RESPONSE:" + ret);
		logger.info("请求处理时长(毫秒):" + (System.currentTimeMillis() - startTime.get()));
		logger.info("---------------返回内容---------------");
	}
}

六、保存日志到数据库(留坑)

方案: 使用spring的aop技术切到自定义注解上,针对不同注解标志进行参数解析,记录日志。
springboot—spring aop 实现系统操作日志记录存储到数据库


references:
springboot集成AOP管理日志
spring-boot使用AOP统一处理日志

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值