end: 包调整、日志MDC

This commit is contained in:
wangiegie@gmail.com 2017-12-04 15:48:07 +08:00
parent d641b96879
commit 781a355261
14 changed files with 156 additions and 166 deletions

View File

@ -1,7 +1,7 @@
package com.github.pig.admin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;

View File

@ -1,4 +1,4 @@
package com.github.pig.admin.config;
package com.github.pig.admin.common.config;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;

View File

@ -1,4 +1,4 @@
package com.github.pig.admin.listener;
package com.github.pig.admin.common.listener;
import com.github.pig.admin.service.SysLogService;
import com.github.pig.common.constant.CommonConstant;
@ -6,6 +6,7 @@ import com.github.pig.common.entity.SysLog;
import com.github.pig.common.util.UserUtils;
import com.github.pig.common.vo.LogVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
@ -18,6 +19,8 @@ import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = CommonConstant.LOG_QUEUE)
public class LogReceiveListener {
private static final String KEY_USER = "user";
@Autowired
private SysLogService sysLogService;
@ -26,8 +29,10 @@ public class LogReceiveListener {
SysLog sysLog = logVo.getSysLog();
if (StringUtils.isNotEmpty(logVo.getToken())) {
String username = UserUtils.getUserName(logVo.getToken());
MDC.put(KEY_USER, username);
sysLog.setCreateBy(username);
sysLogService.insert(sysLog);
MDC.remove(KEY_USER);
}
sysLogService.insert(sysLog);
}
}

View File

@ -1,4 +1,4 @@
package com.github.pig.admin.util;
package com.github.pig.admin.common.util;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;

View File

@ -1,4 +1,4 @@
package com.github.pig.admin.util;
package com.github.pig.admin.common.util;
import com.github.pig.admin.dto.TreeNode;

View File

@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.service.SysLogService;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.entity.SysLog;
import com.github.pig.common.util.UserUtils;
import com.github.pig.common.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@ -28,7 +29,7 @@ public class LogController extends BaseController {
@PostMapping
public Boolean log(@RequestBody SysLog sysLog) {
sysLog.setCreateBy(getUser());
sysLog.setCreateBy(UserUtils.getUserName());
return sysLogService.insert(sysLog);
}

View File

@ -4,7 +4,7 @@ import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pig.admin.dto.MenuTree;
import com.github.pig.admin.entity.SysMenu;
import com.github.pig.admin.service.SysMenuService;
import com.github.pig.admin.util.TreeUtil;
import com.github.pig.admin.common.util.TreeUtil;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.vo.MenuVo;
import com.github.pig.common.web.BaseController;

View File

@ -10,8 +10,12 @@ import com.github.pig.admin.service.SysMenuService;
import com.github.pig.admin.service.SysUserRoleService;
import com.github.pig.admin.service.UserService;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.UserUtils;
import com.github.pig.common.vo.UserVo;
import com.github.pig.common.web.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@ -39,8 +43,9 @@ public class UserController extends BaseController {
*/
@GetMapping("/info")
public UserInfo user() {
logger.info("hahahahahahahahah------------------->");
SysUser condition = new SysUser();
condition.setUsername(getUser());
condition.setUsername(UserUtils.getUserName());
SysUser sysUser = userService.selectOne(new EntityWrapper<>(condition));
UserInfo userInfo = new UserInfo();

View File

@ -1,160 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">
<!-- 从高到地低 OFF 、 FATAL 、 ERROR 、 WARN 、 INFO 、 DEBUG 、 TRACE 、 ALL -->
<!-- 日志输出规则 根据当前ROOT 级别日志输出时级别高于root默认的级别时 会输出 -->
<!-- 以下 每个配置的 filter 是过滤掉输出文件里面会出现高级别文件依然出现低级别的日志信息通过filter 过滤只记录本级别的日志-->
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<resetJUL>true</resetJUL>
</contextListener>
<property name="appname" value="pig"/>
<!-- 属性描述 scan性设置为true时配置文件如果发生改变将会被重新加载默认值为true scanPeriod:设置监测配置文件是否有修改的时间间隔如果没有给出时间单位默认单位是毫秒。当scan为true时此属性生效。默认的时间间隔为1分钟。
debug:当此属性设置为true时将打印出logback内部日志信息实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 定义日志文件 输入位置 -->
<property name="log_dir" value="logs/ev_cmdb"/>
<!-- 日志最大的历史 30天 -->
<property name="maxHistory" value="30"/>
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 -->
<property name="LOG_HOME" value="logs/ev_cmdb"/>
<!-- ConsoleAppender 控制台输出日志 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- 对日志进行格式化 -->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger -%msg%n</pattern>
</encoder>
</appender>
<!-- ERROR级别日志 -->
<!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 RollingFileAppender-->
<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器只记录WARN级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<!-- 最常用的滚动策略,它根据时间来制定滚动策略.既负责滚动也负责出发滚动 -->
<!-- 按照每天生成日志文件 -->
<appender name="file"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志输出位置 可相对、和绝对路径 -->
<fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/error-log.log</fileNamePattern>
<!-- 可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件假设设置每个月滚动,且<maxHistory>是6
则只保存最近6个月的文件删除之前的旧文件。注意删除旧文件是那些为了归档而创建的目录也会被删除-->
<maxHistory>${maxHistory}</maxHistory>
<!--日志文件输出的文件名 -->
<FileNamePattern>${LOG_HOME}/${appname}.log.%d{yyyy-MM-dd}.log
</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<!--格式化输出:%d表示日期%thread表示线程名%-5level级别从左显示5个字符宽度%msg日志消息%n是换行符 -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} 【%X{user}】[%thread] %-5level %logger{50} -%msg%n
</pattern>
</layout>
<!--日志文件最大的大小 -->
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- 按照固定窗口模式生成日志文件当文件大于20MB时生成新的日志文件。窗口大小是1到3当保存了3个归档文件后将覆盖最早的日志。
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/.log.zip</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>3</maxIndex>
</rollingPolicy> -->
<!-- 查看当前活动文件的大小如果超过指定大小会告知RollingFileAppender 触发当前活动文件滚动
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy> -->
<!-- To enable JMX Management -->
<jmxConfigurator/>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} 【%X{user}】 [%thread] %-5level %logger{36} -%msg%n</pattern>
</encoder>
</appender>
<!-- WARN级别日志 appender -->
<appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器只记录WARN级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/warn-log.log
</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- INFO级别日志 appender -->
<appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器只记录INFO级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/info-log.log
</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- DEBUG级别日志 appender -->
<appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器只记录DEBUG级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/debug-log.log
</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- TRACE级别日志 appender -->
<appender name="TRACE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器只记录ERROR级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>TRACE</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/trace-log.log
</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<logger name="java.sql.PreparedStatement" value="DEBUG"/>
<logger name="java.sql.Connection" value="DEBUG"/>
<logger name="java.sql.Statement" value="DEBUG"/>
<logger name="com.ibatis" value="DEBUG"/>
<logger name="com.ibatis.common.jdbc.SimpleDataSource" value="DEBUG"/>
<logger name="com.ibatis.common.jdbc.ScriptRunner" level="DEBUG"/>
<logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate" level="DEBUG"/>
<logger name="org.springframework.amqp.rabbit" level="INFO"/>
<!-- root级别 DEBUG -->
<root level="DEBUG">
<!-- 控制台输出 -->
<appender-ref ref="STDOUT"/>
<!-- 文件输出 -->
<appender-ref ref="ERROR"/>
<appender-ref ref="INFO"/>
<appender-ref ref="WARN"/>
<appender-ref ref="DEBUG"/>
<appender-ref ref="TRACE"/>
<logger name="com.github.pig" level="debug">
<!-- wenjie delete <appender-ref ref="file" /> <appender-ref ref="console"
/> -->
</logger>
<root level="info">
<!--
<appender-ref ref="file" />
-->
<appender-ref ref="console"/>
</root>
</configuration>

View File

@ -0,0 +1,20 @@
package com.github.pig.common.config;
import com.github.pig.common.filter.UserFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author lengleng
* @date 2017/12/4
*/
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registration = new FilterRegistrationBean(new UserFilter());
registration.addUrlPatterns("/*");
return registration;
}
}

View File

@ -0,0 +1,36 @@
package com.github.pig.common.filter;
import com.github.pig.common.util.UserUtils;
import org.apache.commons.lang.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @author lengleng
* @date 2017/12/4
*/
public class UserFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String username = UserUtils.getUserName((HttpServletRequest) request);
if (StringUtils.isNotEmpty(username)) {
UserUtils.setUser(username);
}
chain.doFilter(request, response);
if (StringUtils.isNotEmpty(username)) {
UserUtils.clearAllUserInfo();
}
}
@Override
public void destroy() {
}
}

View File

@ -6,6 +6,7 @@ import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
@ -18,6 +19,8 @@ import java.util.Base64;
*/
public class UserUtils {
private static Logger logger = LoggerFactory.getLogger(UserUtils.class);
private static final ThreadLocal<String> tlUser = new ThreadLocal<String>();
private static final String KEY_USER = "user";
/**
@ -33,6 +36,9 @@ public class UserUtils {
return username;
}
String token = StringUtils.substringAfter(authorization, CommonConstant.TOKEN_SPLIT);
if (StringUtils.isEmpty(token)) {
return username;
}
String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
try {
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
@ -46,12 +52,15 @@ public class UserUtils {
/**
* 通过token 获取用户名
*
* @param token
* @param authorization
* @return
*/
public static String getUserName(String authorization) {
String username = "";
String token = StringUtils.substringAfter(authorization, CommonConstant.TOKEN_SPLIT);
if (StringUtils.isEmpty(token)) {
return username;
}
String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
try {
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
@ -61,4 +70,29 @@ public class UserUtils {
}
return username;
}
/**
* 设置用户信息
*
* @param username
*/
public static void setUser(String username) {
tlUser.set(username);
MDC.put(KEY_USER, username);
}
/**
* 如果没有登录返回null
*
* @return
*/
public static String getUserName() {
return tlUser.get();
}
public static void clearAllUserInfo() {
tlUser.remove();
MDC.remove(KEY_USER);
}
}

View File

@ -1,7 +1,6 @@
package com.github.pig.common.web;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.UserUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
@ -16,18 +15,11 @@ import java.util.List;
* @date 2017/10/28
*/
public class BaseController {
public org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());
@Autowired
private HttpServletRequest request;
/**
* 根据请求heard中的token获取用户
*
* @return 用户名
*/
public String getUser() {
return UserUtils.getUserName(request);
}
/**
* 根据请求heard中的token获取用户角色
*

View File

@ -5,6 +5,7 @@ import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -18,7 +19,8 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst
*/
@Component
public class LoggerFilter extends ZuulFilter {
private Logger logger = LoggerFactory.getLogger(LoggerFilter.class);
private static final String KEY_USER = "user";
@Autowired
private LogSendService logSendService;
@ -39,7 +41,9 @@ public class LoggerFilter extends ZuulFilter {
@Override
public Object run() {
MDC.put(KEY_USER, "冷冷");
logSendService.send(RequestContext.getCurrentContext());
MDC.remove(KEY_USER);
return null;
}
}