首页 > 其他分享 >aop切面记日志

aop切面记日志

时间:2022-09-21 15:59:44浏览次数:54  
标签:String annotation 切面 aop import 日志 com operation Log

package com.netauth.utils.component;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
	
	/**  
	 * <p>Title: logtype</p>  
	 * <p>Description: 日志类型 默认为"" 即为管理员操作日志,注册日志="registeruser"</p>  
	 * @return  
	 * @author lbw
	 * @date 2022年7月8日
	 */  
	String logtype() default "";
	
	/**  
	 * <p>Title: paramKey</p>  
	 * <p>Description: 记录日志信息 需要从参数中取值当做日志参数时 设置此参数为所需参数key</p>  
	 * @return  
	 * @author lbw
	 * @date 2022年7月8日
	 */  
	String paramKey() default "";
}

  

package com.infosec.config;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.infosec.user.compoent.UserInternationKeyConst;
import com.netauth.api.logcollection.Log;
import com.netauth.utils.Const;
import com.netauth.utils.GetMacAddress;
import com.netauth.utils.LogConst;
import com.netauth.utils.component.LocaleMessageSourceService;
import com.netauth.utils.component.LogAnnotation;
import com.netauth.utils.currentuser.LoginUserUtil;
import com.netauth.utils.gateway.GatewayConst;
import com.netauth.utils.jsonresult.JsonErrotCode;
import com.netauth.utils.jsonresult.JsonResult;

import io.swagger.annotations.ApiOperation;
 
@Aspect
@Configuration
public class LogAspect {
	
	@Resource
	private LocaleMessageSourceService localeMessageSourceService;
 
	@Autowired
	private Log log;
	
    public LogAspect() {
    }
 
    @Pointcut("@within(com.netauth.utils.component.LogAnnotation) || @annotation(com.netauth.utils.component.LogAnnotation)")
    public void pointCutMethod() {
    }
 
    // 声明环绕通知
    @Around("pointCutMethod()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Long startTime = System.currentTimeMillis();
        // 获取request对象
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        Object ret = null;
        if(sra == null) {
        	ret = pjp.proceed();
        	return ret;
        }
        
        HttpServletRequest request = sra.getRequest();
        String requestURI = request.getServletPath();
        Map<String, Object> localUser = LoginUserUtil.getLoginUser(request);
        boolean exceptionFlag = false;
        Exception exportEx = null;
        try {
        	ret = pjp.proceed();
		} catch (Exception e) {
			if(requestURI != null && requestURI.indexOf("/export/") != -1) {
				exceptionFlag = true;
				exportEx = e;
			}else {
				throw e;
			}
		}
       
        Long endTime = System.currentTimeMillis();
        //设置请求路径
        if(StringUtils.isEmpty(requestURI) || requestURI.contains(GatewayConst.CLIENT_NO_FILTER)) {
        	//
        }else {
        	addLog(request,requestURI,exceptionFlag,localUser,pjp,endTime-startTime,ret);
        }
        if(exceptionFlag) {
        	throw exportEx;
        }
        return ret;
    }
 
   //获取参数名和参数值
    public Map<String, Object> getParam(ProceedingJoinPoint proceedingJoinPoint) {
        Map<String, Object> map = new HashMap<String, Object>();
        Object[] values = proceedingJoinPoint.getArgs();
        String[] names = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterNames();
        for (int i = 0; i < names.length; i++) {
            map.put(names[i], values[i]);
        }
        return map;
    }

 
    private void addLog(HttpServletRequest request,String requestURI,boolean exceptionFlag,Map<String, Object> localUser,ProceedingJoinPoint pjp,Long time,Object ret) throws IOException {
    	String apiName;
    	String logType;
    	MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
        apiName = Objects.nonNull(apiOperation) ? apiOperation.value() : "";
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        if(annotation == null) {
        	annotation = pjp.getTarget().getClass().getAnnotation(LogAnnotation.class);
        }
        logType = annotation.logtype();
        
    	String msg = "";
    	String code = "";
    	String model = "";
		String appName = "";
		String operation = "";
		int logLevel = Log.LOG_LEVEL_WARN;
		int result = Log.RESULT_FAIULE;
		String[] split = requestURI.split("/");
		appName = !StringUtils.isEmpty(split[1])? split[1] : appName;
		model = !StringUtils.isEmpty(split[2])? split[2] : model;
		operation = !StringUtils.isEmpty(split[3])? split[3] : operation;
    	
		JsonResult res = null;
		if(ret!= null && ret instanceof JsonResult) {
        	res =  (JsonResult) ret ;
            code = res.getCode(); 
            msg = res.getMsg(); 
        }
		
		//没有响应  且操作类型为导出 
		if(ret == null && "export".equals(operation)) {
			//根据是否异常来设置code和msg
			if(exceptionFlag) {
				code = JsonErrotCode.FAIL_CODE;
			}else {
	        	code = JsonErrotCode.SUCCESS_CODE;
			}
		}
		
        String localUserLoginName = "";
  		String localUserName = "";
  		String localUserRoles = "";
  		String localUserDn = "";
  		String userClientIp = "";
		
        //根据响应code首字母判断成功失败
        if(code.startsWith("I")) {
        	logLevel =  Log.LOG_LEVEL_INFO;
        	result = Log.RESULT_SUCCESS;
	    	if(StringUtils.isEmpty(msg)) {
	    		msg = apiName + "成功";
	        }
        } else if(code.startsWith("W")) {
        	logLevel =  Log.LOG_LEVEL_WARN;
        	result = Log.RESULT_FAIULE;
        	if(StringUtils.isEmpty(msg)) {
	    		msg = apiName + "失败";
	        }
        } else if(code.startsWith("E")) {
        	logLevel =  Log.LOG_LEVEL_ERROR;
        	result = Log.RESULT_FAIULE;
    		msg = apiName+" 异常 " +  (StringUtils.isEmpty(msg) ? "" : msg);
    		if(res != null) {
    			res.setMsg(localeMessageSourceService.getMessage(UserInternationKeyConst.SYS_EXCEPTION));
    		}
        }
  		
        switch (operation) {
		case "get":
			operation = Log.HOWS_READ; break;
		case "update":
			operation = Log.HOWS_MODIFY; break;
		case "del":
			operation = Log.HOWS_DEL; break;
		case "add":
			operation = Log.HOWS_ADD; break;
		case "login":
			operation = Log.HOWS_LOGIN; break;
		case "export":
			operation = Log.HOWS_EXPORT; break;
		case "import":
			operation = Log.HOWS_IMPORT; break;
		case "download":
			operation = Log.HOWS_DOWNLOAD; break;
		default:
			operation = Log.HOWS_OTHERS; break;
		}
        
        
        //没有登录调用接口(对外API,注册)
        if (localUser == null) {
        	
        	if( LogConst.LOGTYPE_API.equals(appName) ) {
        		//对外API
        		String header = request.getHeader(Const.APPID);
    			localUserLoginName = header;
            	localUserName = header;
            	appName = header;
            	model = LogConst.LOGTYPE_API;
        	} else if(LogConst.MODEL_FLAG_PORTAL.equals(logType) ) {
        		if(LogConst.MODEL_FLAG_USER.equals(appName)) {
        			model = Const.MODEL_USER;
        		} else if(LogConst.MODEL_FLAG_SMS.equals(appName)) {
        			model = Const.MODEL_SMS;
        		} else if(LogConst.MODEL_FLAG_APPROVAL.equals(appName)) {
        			model = Const.MODEL_APPROVAL;
        		} else if(LogConst.MODEL_FLAG_PORTALMANAGER.equals(appName)) {
        			model = Const.MODEL_PORTAL;
        		}
        		if(requestURI.indexOf("/get/") != -1) {
        			operation = Log.HOWS_READ;
        		}else if (requestURI.indexOf("/update/") != -1) {
        			operation = Log.HOWS_MODIFY;
        		}
        		localUserRoles = "commonuser";
        		//普通用户调用日志 没有登录时取参数内的登录名做日志参数
        		 String paramKey = annotation.paramKey();
        		 Map<String, Object> param = getParam(pjp);
        		 localUserLoginName = (String) param.get(paramKey);
        		 localUserName = localUserLoginName;
        		 localUserDn = localUserLoginName;
        	} 
        	userClientIp = GetMacAddress.getIpAddr(request);
  		}else {
	  		localUserLoginName = (String) localUser.get(LoginUserUtil.USER_LOGINNAME);
	  		localUserName = (String) localUser.get(LoginUserUtil.USER_USERNAME);
	  		localUserRoles = (String) localUser.get(LoginUserUtil.USER_SYSADMIN);
	  		localUserDn = (String) localUser.get(LoginUserUtil.USER_DEPTDN);
	  		userClientIp = (String) localUser.get(LoginUserUtil.USER_CLIENTIP);
  		}
  		JSONObject json = new JSONObject();
  		json.put("logLevel", logLevel);
  		json.put("model", model);
  		json.put("localUserLoginName", localUserLoginName);
  		json.put("userClientIp", userClientIp);
  		json.put("operation", operation);
  		json.put("result", result);
  		json.put("msg", msg);
  		json.put("localUserName", localUserName);
  		json.put("localUserRoles", localUserRoles);
  		json.put("localUserDn", localUserDn);
  		json.put("appName", appName);
  		json.put("requestURI", requestURI);
    	log.writeLog(this.getClass().getName(), logLevel, model, localUserLoginName, userClientIp,
    			operation, result, msg, localUserName, localUserRoles, localUserDn,
    			appName,requestURI);//此处就是调用后面保存日志逻辑
    }
}

  

标签:String,annotation,切面,aop,import,日志,com,operation,Log
From: https://www.cnblogs.com/cuijinlong/p/16715833.html

相关文章

  • 第十章 ES定时删除日志索引脚本
    一、编写脚本[root@ES-Log-1~]#vimdelete_es_indices.sh#!/bin/bash#主机IPhost_ip="172.16.1.24:9200"#超过10天的索引将要删除delete_overday=10functiond......
  • 第八章 filebeat收集日志与kibana画图
    一、filebeat收集单日志到本地文件1.配置#编辑Filebeat配置文件[root@web01~]#vim/etc/filebeat/filebeat.ymlfilebeat.inputs:-type:logenabled:truepat......
  • oracle biee 日常运维,BIEE日志及几个重要的配置文件
    转至:https://blog.csdn.net/weixin_35717696/article/details/116386729BIEE目录有很多log日志,可以很方便的定位错误,分别为:1.BI的安装日志:~\OracleBI\log\install.log2.......
  • linux改源日志1.0
    centos改源  源文件/etc/yum.repo.d/centos_*.repo1yum-yinstallwget #下载wget 用于下载源文件2cd/etc/yum.repo.d#3 mkdir bak;cp......
  • mybatisplus打印SQL日志 【mybatisplus专栏】
    一、mybatisplus如何打印SQL日志:在SpringBoot项目中添加以下配置#方式一mybatis-plus:configuration:log-impl:org.apache.ibatis.logging.stdout.StdOutImp......
  • ssh服务器拒绝了密码。log日志failed password for root
    环境:centos7.6软件版本:xshell5问题描述:通过xshell登录linux服务器,报错‘ssh服务器拒绝了密码’。解决过程:百度了一下,说是可能ssh配置文件有问题,修改‘PermitRootLogin......
  • MySQL维护之日志文件
    MySQL数据库中常见的日志文件有错误日志(ErrorLog)、二进制日志(BinaryLog)、慢查询日志(SlowQueryLog)、全查询日志(GeneralQueryLog)、中继日志(RelayLog)和事务日志。......
  • ELK搭建自己的日志系统
    在开发过程中,日志会直接在控制台打印方便查看,而生产环境下应该保存为文件,以便以后查阅。随着项目规模越来越大,导致日志数据累计巨大,想要快速从文件中找到几乎是不可能......
  • Mysql系列---【使用慢日志查询分析sql语句】
    1.查看慢日志是否开启mysql>showvariableslike'slow_query%';+---------------------------+----------------------------------+|Variable_name|......
  • 音响配置日志
    音响配置日志开始初始化SDKInittcpNetwork-----------Currentnetworkmode:WAN-----------Networkinitializing,pleasewait...网络初始化成功!Music=D:/m1.m......