springboot控制台⽇志打印到⽇志⽂件(请求路径,执⾏sql,参数等)经过⼏天的尝试 重终于把这个东西肝出来了
⽬录结构
我添加太多pom了 忘记有哪些了 也懒得了 也就是常⽤的那⼏个吧 依赖pom ⼩伙⼦们⾃⼰添加吧
⾸先你要把你项⽬跑起来 配置数据源如下
server:
port:7001
logging:
level:
root: info
com.joe: debug
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: sql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/world?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT %2b8&serverTimezone=Asia/Shanghai
username: root
password: root
initialSize:1
minIdle:3
maxActive:20
# 配置获取连接等待超时的时间
maxWait:60000
# 配置间隔多久才进⾏⼀次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis:60000
# 配置⼀个连接在池中最⼩⽣存的时间,单位是毫秒
minEvictableIdleTimeMillis:30000
validationQuery: select 'x'
testWhileIdle:true
testOnBorrow:false
testOnReturn:false
# 打开PSCache,并且指定每个连接上PSCache的⼤⼩
poolPreparedStatements:true
maxPoolPreparedStatementPerConnectionSize:20
# 配置监控统计拦截的filters,去掉后监控界⾯sql⽆法统计,'wall'⽤于防⽕墙
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: Sql=true;druid.stat.slowSqlMillis=5000
hikari:
connection-test-query: select 1
connection-timeout:60000
idle-timeout:500000
max-lifetime:540000
maximum-pool-size:12
minimum-idle:10
pool-name: GGLiliKariPool
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
thymeleaf:
check-template:false
check-template-location:false
mybatis:
mapperLocations: classpath:com/joe/testonedemo/mapper/*.xml
type-aliases-package: ity # 实体类所在的位置
pagehelper:
helperDialect: mysql
reasonable:true
supportMethodsArguments:true
params: count=countSql
接下来 启动类要添加三个注解
@ServletComponentScan
@SpringBootApplication
@EnableCaching
1、 @ServletComponentScan的作⽤是让Servlet、Filter、Listener可以直接通过@WebServlet、@WebFilter、@WebListener注解⾃动注册 ⽆需其他代码
2、 @SpringBootApplication 也就是 Sprnig Boot项⽬的核⼼注解了 ⽬的是开启⾃动配置
3、 @EnableCaching 注解是spring framework中的注解驱动的缓存管理功能
然后:
添加相应的业务代码 让它跑起来 对 就像这样跑起来
接着要在resources ⽂件夹下添加⼀个
代码如下
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true"scanPeriod="60 seconds"debug="false">
<contextName>logback</contextName>
<property name="CONSOLE_LOG_PATTERN"value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) |%highlight(%-5level)|%blue(%thread) |%blue(%file:%lin e) |%green(%logger) |%cyan(%msg%n)"/>
<!--输出到控制台-->
<appender name="console"class="ch.ConsoleAppender">
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
</encoder>
</appender>
<!--按天⽣成⽇志-->
<appender name="logFile"class="ch.olling.RollingFileAppender">
<Prudent>true</Prudent>
<rollingPolicy class="ch.olling.TimeBasedRollingPolicy">
<FileNamePattern>
applog/%d{yyyy-MM-dd}/%d{yyyy-MM-dd}.log
</FileNamePattern>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} -%msg%n
</Pattern>
</layout>
</appender>
<logger name="com.kinghomiddle"additivity="false">
<appender-ref ref="console"/>
<appender-ref ref="logFile"/>
</logger>
<root level="error">
<appender-ref ref="console"/>
<appender-ref ref="logFile"/>
</root>
</configuration>
注意我没有设置⽇志有效期(⾃动删除⽇志)
然后再重启项⽬ 效果如下
就会变成酱⼦
在顶级包下会出现⼀个 如图
⾥⾯就是你的启动⽇志 再调⽤接⼝ 会发现只有打印sql ⽽没有请求路径 这个时候就要⽤到了创建⼀个包 叫config 其实 顺便这个包叫啥都⾏ 再顺便创建⼀个类
@Slf4j
@Configuration
public class LoggingFilterConfig implements Filter {
@Bean
public FilterRegistrationBean registrationBean(){
FilterRegistrationBean filter =new FilterRegistrationBean(new LoggingFilterConfig());
filter.addUrlPatterns("/*");
//多个过滤器时执⾏顺序
// 最⾼级别。
filter.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
return filter;
}
@Override
public void init(FilterConfig filterConfig)throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)throws IOException, ServletException {
HttpServletRequest req =(HttpServletRequest)request;
HttpServletRequest req =(HttpServletRequest)request;
Map<String, Object> map =new HashMap<String, Object>();
// Get request URL.
map.put("URL", RequestURL());
springboot是啥map.put("Method", Method());
map.put("Protocol",Protocol());
/
/ 获取header信息
List<Map<String, String>> headerList =new ArrayList<>();
Map<String, String> headerMaps =new HashMap<String, String>();
for(Enumeration<String> enu = HeaderNames(); enu.hasMoreElements();){
String name = Element();
headerMaps.put(Header(name));
}
headerList.add(headerMaps);
map.put("headers", headerList);
//获取parameters信息
List<Map<String, String>> parameterList =new ArrayList<>();
Map<String, String> parameterMaps =new HashMap<String, String>();
for(Enumeration<String> names = ParameterNames(); names.hasMoreElements();){ String name = Element();
parameterMaps.put(name, Parameter(name));
}
parameterList.add(parameterMaps);
map.put("parameters", parameterList);
String line ="";
int idx = RequestURL().indexOf("?");
if(idx !=-1){
line = RequestURL().substring(idx +1);
}else{
line =null;
}
if(line !=null){
map.put("Context",new String[]{ line });
}
log.info("请求路径: "+("URL")));
// log.JSONString(map));
chain.doFilter(request, response);
log.ContentType());
}
@Override
public void destroy(){
}
}
把这个代码扔进去就好了
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论