Commit 701a022b authored by 喻春霖's avatar 喻春霖

fied

parents 97156069 43d5f7ef
......@@ -17,6 +17,25 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<exclusions>
<!-- 排除自带的logback依赖 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
......
......@@ -18,7 +18,8 @@ import com.chineseall.eden.authcenter.log.model.AuthLog;
import com.chineseall.eden.authcenter.log.model.LogUserInfo;
import com.chineseall.eden.authcenter.log.service.AuthLogService;
import com.sh.chineseall.framework.core.http.resttemplate.MyRestTemplate;
import org.apache.log4j.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
......@@ -39,7 +40,7 @@ import java.util.stream.Collectors;
@RequestMapping("/")
public class AuthController {
Logger logger = Logger.getLogger(AuthController.class);
Logger logger = LoggerFactory.getLogger(AuthController.class);
// @Autowired
// private OauthClient oauthClient;
......
package com.chineseall.eden.authcenter.agent.controller;
import com.alibaba.fastjson.JSON;
import com.chineseall.eden.authcenter.log.util.BusinessLogUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@Controller
@RequestMapping("log")
public class LogController {
private static final Logger logger = LoggerFactory.getLogger(LogController.class);
@GetMapping("test")
@ResponseBody
public void test(HttpServletRequest request){
Map<String, String[]> params = request.getParameterMap();
BusinessLogUtils.info(params);
logger.info(" ==== logs : " + JSON.toJSONString(params));
}
}
......@@ -14,7 +14,8 @@ import com.chineseall.eden.authcenter.log.model.AuthLog;
import com.chineseall.eden.authcenter.log.model.LogUserInfo;
import com.chineseall.eden.authcenter.log.service.AuthLogService;
import com.sh.chineseall.framework.core.http.resttemplate.MyRestTemplate;
import org.apache.log4j.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
......@@ -38,7 +39,7 @@ import java.util.stream.Collectors;
@RequestMapping("/ucenter")
public class UcenterController {
Logger logger = Logger.getLogger(UcenterController.class);
Logger logger = LoggerFactory.getLogger(UcenterController.class);
@Autowired
private OauthClient oauthClient;
......
package com.chineseall.eden.authcenter.agent.interceptor;
import com.chineseall.eden.authcenter.log.util.RequestResponseHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class AccessInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
RequestResponseHolder.set(httpServletRequest, httpServletResponse);
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
RequestResponseHolder.remove();
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
......@@ -14,11 +14,18 @@ public class ApiInterceptorConfig extends WebMvcConfigurerAdapter {
@Autowired
ApiInterceptor apiInterceptor;
@Autowired
AccessInterceptor accessInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册TestInterceptor拦截器
InterceptorRegistration accessRegistration = registry.addInterceptor(accessInterceptor);
accessRegistration.addPathPatterns("/**");
InterceptorRegistration registration = registry.addInterceptor(apiInterceptor);
registration.addPathPatterns("/config/**"); //
}
@Override
......
server:
port: 9600
context-path: /authcenter
logging:
config: classpath:log4j.xml
spring:
application:
name: eden-authcenter-agent
......
server:
port: 9600
context-path: /authcenter
logging:
config: classpath:log4j.xml
spring:
application:
name: eden-authcenter-agent
......
......@@ -2,16 +2,16 @@
"mongo": [
{
"connectionName": "mongo",
"host": "dds-uf61aa933d7006b41.mongodb.rds.aliyuncs.com",
"port": 3717,
"replicaSet": "dds-uf61aa933d7006b41.mongodb.rds.aliyuncs.com:3717",
"host": "47.93.119.144",
"port": 27017,
"replicaSet": "47.93.119.144:27017",
"maxConnectionsPerHost": 3000,
"threadsAllowedToBlockForConnectionMultiplier": 10,
"authentication": true,
"connectTimeout": 10000,
"password": "ChineseAll&0219",
"userName": "dsuser",
"dbName": "dslog"
"password": "yuchu666",
"userName": "admin",
"dbName": "admin"
}
]
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<configuration monitorInterval="5">
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--变量配置-->
<Properties>
<!-- 格式化输出:%date表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符-->
<!-- %logger{36} 表示 Logger 名字最长36个字符 -->
<property name="LOG_PATTERN" value="%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />
<!-- 定义日志存储的路径 -->
<property name="FILE_PATH" value="/Users/wangsong/data/logs/" />
<property name="FILE_NAME" value="info" />
<property name="BUSINESS_FILE_NAME" value="business_info" />
</Properties>
<appenders>
<console name="Console" target="SYSTEM_OUT">
<!--输出日志的格式-->
<PatternLayout pattern="${LOG_PATTERN}"/>
<!--控制台只输出level及其以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
</console>
<!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,适合临时测试用-->
<File name="Filelog" fileName="${FILE_PATH}/test.log" append="false">
<PatternLayout pattern="${LOG_PATTERN}"/>
</File>
<!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileInfo" fileName="${FILE_PATH}/info.log" filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次,1 天-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="300"/>
</RollingFile>
<!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingBusinessFileInfo" fileName="${FILE_PATH}/business_info.log" filePattern="${FILE_PATH}/${BUSINESS_FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="%msg%n"/>
<Policies>
<!--interval属性用来指定多久滚动一次,1 天-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="300"/>
</RollingFile>
<!-- 这个会打印出所有的warn及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileWarn" fileName="${FILE_PATH}/warn.log" filePattern="${FILE_PATH}/${FILE_NAME}-WARN-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次,1天-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="300"/>
</RollingFile>
<!-- 这个会打印出所有的error及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileError" fileName="${FILE_PATH}/error.log" filePattern="${FILE_PATH}/${FILE_NAME}-ERROR-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次,1天-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="300"/>
</RollingFile>
</appenders>
<!--Logger节点用来单独指定日志的形式,比如要为指定包下的class指定不同的日志级别等。-->
<!--然后定义loggers,只有定义了logger并引入的appender,appender才会生效-->
<loggers>
<!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
<logger name="org.mongodb" level="info" additivity="false">
<AppenderRef ref="Console"/>
</logger>
<!-- 启动日志打到控制台 -->
<Logger name="org.springframework" level="info" additivity="false">
<AppenderRef ref="Console"/>
</Logger>
<!--监控系统信息-->
<!--若是additivity设为false,则 子Logger 只会在自己的appender里输出,而不会在 父Logger 的appender里输出。-->
<Logger name="com.chineseall.eden.authcenter.log.util.BusinessLogUtils" level="info" additivity="true">
<AppenderRef ref="RollingBusinessFileInfo"/>
</Logger>
<root level="info">
<appender-ref ref="Console"/>
<appender-ref ref="Filelog"/>
<appender-ref ref="RollingFileInfo"/>
<appender-ref ref="RollingFileWarn"/>
<appender-ref ref="RollingFileError"/>
</root>
</loggers>
</configuration>
......@@ -15,6 +15,21 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<exclusions>
<!-- 排除自带的logback依赖 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
......@@ -79,6 +94,12 @@
<type>jar</type>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.22</version>
</dependency>
</dependencies>
......
package com.chineseall.eden.authcenter.log.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.sh.chineseall.framework.core.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.chineseall.eden.authcenter.log.dao.AuthLogDao;
import com.chineseall.eden.authcenter.log.model.AuthLog;
import com.chineseall.eden.authcenter.log.model.AuthLogHourCount;
import com.chineseall.eden.authcenter.log.service.AuthLogService;
import com.chineseall.eden.authcenter.log.util.BusinessLogUtils;
import com.chineseall.eden.authcenter.log.util.RequestResponseHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
......@@ -31,6 +35,19 @@ public class AuthLogServiceImpl implements AuthLogService {
authLog.setCreateTime(new Date());
authLogDao.insert(authLog);
}
addBusinessLog(authLog);
}
private void addBusinessLog(AuthLog authLog){
RequestResponseHolder holder = RequestResponseHolder.get();
Map<String, Object> dataMap = BeanUtil.beanToMap(authLog);
dataMap.put("user-agent", holder.getRequestUserAgent());
dataMap.put("remote-address", holder.getRequestRemoteAddress());
dataMap.put("referer", holder.getRequestReferer());
dataMap.put("ip", holder.getIpAddress());
dataMap.put("request", holder.getRequestMethod() + " " + holder.getRequestContextPath());
dataMap.put("timestamp", System.currentTimeMillis());
BusinessLogUtils.info(JSON.toJSONString(dataMap));
}
@Override
......
package com.chineseall.eden.authcenter.log.util;
import cn.sh.chineseall.framework.core.util.MapUtils;
import cn.sh.chineseall.framework.core.util.StringUtils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class BusinessLogUtils {
private static final Logger logger = LoggerFactory.getLogger(BusinessLogUtils.class);
public static void info(Map<String, String[]> data){
if(MapUtils.isEmpty(data)){
return;
}
logger.info(JSON.toJSONString(data));
}
public static void info(String jsonData){
if(StringUtils.isBlank(jsonData)){
return;
}
logger.info(jsonData);
}
}
package com.chineseall.eden.authcenter.log.util;
import cn.sh.chineseall.framework.core.repackaged.org.apache.commons.lang3.StringUtils;
import lombok.Getter;
import lombok.Setter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
@Getter
@Setter
public class RequestResponseHolder {
public static final ThreadLocal<RequestResponseHolder> requestResponseLocal = new ThreadLocal<>();
private HttpServletRequest request;
private HttpServletResponse response;
public Map<String, String> getRequestHeaderMap(){
Map<String, String> requestHeaderMap = new HashMap<>();
Enumeration<String> headerNames = getRequest().getHeaderNames();
while (headerNames.hasMoreElements()){
String headerName = headerNames.nextElement();
String value = getRequest().getHeader(headerName);
requestHeaderMap.put(headerName, value);
}
return requestHeaderMap;
}
public String getRequestUserAgent(){
Map<String, String> headerMap = getRequestHeaderMap();
return headerMap.get("user-agent");
}
public String getRequestRemoteAddress(){
return getRequest().getRemoteAddr();
}
public String getRequestReferer(){
Map<String, String> headerMap = getRequestHeaderMap();
return headerMap.get("referer");
}
public String getRequestMethod(){
return getRequest().getMethod();
}
public String getRequestContextPath(){
return getRequest().getContextPath();
}
public String getIpAddress() {
Map<String, String> headerMap = getRequestHeaderMap();
String Xip = headerMap.get("X-Real-IP");
String XFor = headerMap.get("X-Forwarded-For");
if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = XFor.indexOf(",");
if(index != -1){
return XFor.substring(0,index);
}else{
return XFor;
}
}
XFor = Xip;
if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
return XFor;
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getRemoteAddr();
}
return XFor;
}
public static void set(HttpServletRequest request, HttpServletResponse response){
RequestResponseHolder holder = new RequestResponseHolder();
holder.setRequest(request);
holder.setResponse(response);
requestResponseLocal.set(holder);
}
public static RequestResponseHolder get(){
return requestResponseLocal.get();
}
public static void remove(){
requestResponseLocal.remove();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment