spring aop处理系统操作日志和异常日志,保存到数据库_shanger_1216的博客-程序员宅基地

技术标签: spring-aop  

package com.env.web.zj;


import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;




import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import com.lq.dto.OperatorLog;
import com.lq.service.OperatorLogService;


@Aspect 
@Component 
public class test {


private static Logger logger = Logger.getLogger(test.class);
private static SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


@Autowired
private OperatorLogService<OperatorLog> operatorLogService; //自己创建,用来保存日志信息




@Pointcut("execution(* com.env.web.controller..*.*(..))") //切点
public void webRequestLog(){}


@Pointcut("execution(* com.env.web.controller..*.*(..))") //切点
public void webExceptionLog(){}


@Before("webRequestLog()") 
public void doBefore(JoinPoint joinPoint){
    try {   
    OperatorLog operatorLog = new OperatorLog();
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request= attributes.getRequest();
    String method = request.getMethod();
    //判断是否是post方法,如果是,则记录到日志表中
   // if("POST".equals(method)){
        long beginTime = System.currentTimeMillis();  
        String beanName = joinPoint.getSignature().getDeclaringTypeName(); //方法所在的类名
        String methodName = joinPoint.getSignature().getName()+"-"+method;//方法名
        String param = JSONUtil.obj2StringPretty(request.getParameterMap());//请求参数
        System.out.println(param);
        String uri = request.getRequestURI(); //接口名
        String url = request.getRequestURL().toString(); //url
        String remoteAddr = getIpAddr(request); //ip地址
        String sessionId = request.getSession().getId();
        Integer  uid = (Integer) request.getSession().getAttribute("uid"); //用户id
        if(uid != null){
        }
        operatorLog.setMethod(methodName);
        operatorLog.setBeanName(beanName);
        operatorLog.setIntf(uri);
        operatorLog.setUrl(url);
        Date date = new Date(beginTime);
        operatorLog.setRequestTime(date);
        operatorLog.setRequestIp(remoteAddr);
        operatorLog.setRequestParam(param);
        operatorLogService.save(operatorLog);
        //tlocal.set(operatorLog);
   // }
    } catch (Exception e) {
       e.printStackTrace();
    }
}






/** 
 * 异常通知 用于拦截异常日志 
 * 
 * @param joinPoint 
 * @param e 
 */  
@AfterThrowing(pointcut = "webExceptionLog()", throwing = "e")  
 public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {  
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();  
    HttpSession session = request.getSession();  
    //获取请求ip  
    String ip = request.getRemoteAddr();  
    //获取用户请求方法的参数并序列化为JSON格式字符串   
   try { 
        String method = request.getMethod();
        String param = JSONUtil.obj2StringPretty(request.getParameterMap());
        System.out.println(param);
        String beanName = joinPoint.getSignature().getDeclaringTypeName(); //方法所在的类名
        String methodName = joinPoint.getSignature().getName()+"-"+method;//方法名
        String uri = request.getRequestURI(); //接口名
        String url = request.getRequestURL().toString(); //url
        OperatorLog operatorLog = new OperatorLog();
        operatorLog.setExceptionName(e.getClass().getName());
        operatorLog.setExceptionMsg(e.getMessage());
        operatorLog.setMethod(methodName);
        operatorLog.setUrl(url);
        operatorLog.setIntf(uri);
        operatorLog.setRequestParam(param);
        operatorLog.setBeanName(beanName);
        long beginTime = System.currentTimeMillis();  
        Date date = new Date(beginTime);
        operatorLog.setRequestTime(date);
        operatorLog.setRequestIp(ip);
       
        //保存数据库  
        operatorLogService.save(operatorLog); 
        System.out.println("=====异常通知结束=====");  
   }  catch (Exception ex) {  
        //记录本地异常日志  
        e.printStackTrace();
        logger.error("==异常通知异常==");  
    }  
}  




/*@AfterReturning(returning="result",pointcut = "webRequestLog()")
public void doAfterReturning(Object result){
}
*/


private String getIpAddr(HttpServletRequest request){     
    String ip = request.getHeader("x-forwarded-for");
    if(ip==null || ip.length()==0 || "unknowm".equalsIgnoreCase(ip)){
        ip = request.getHeader("Proxy-Client-IP");
    }
    if(ip==null || ip.length()==0 || "unknowm".equalsIgnoreCase(ip)){
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if(ip==null || ip.length()==0 || "unknowm".equalsIgnoreCase(ip)){
        ip = request.getRemoteAddr();
    }
    return ip;
}
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/shanger_1216/article/details/80941250

智能推荐

理解计算机-程序员宅基地

理解计算机什么是程序 一组指示计算机或其他具有信息处理能力装置执行动作或做出判断的指令,通常用某种程序设计语言编写,运行于某种目标体系结构上。打个比方,一个程序就像一个用汉语(程序设计语言)写下的红烧肉菜谱(程序),用于指导懂汉语和烹饪手法的人(体系结构)来做这个菜。冯·诺依曼计算机体系结构 冯诺依曼理论的要点是:数字计算机的数制采用二进制;计算机应该按照程序顺序执行。 人们把冯诺依曼的这

linux红帽7修改时间,CentOS 7 and RedHat 7 时间同步即chrony服务配置-程序员宅基地

1、安装chrony时间同步服务(系统默认安装)#yum install chrony可以先查询一下是否有安装:[root@localhost etc]# rpm -qa |grep chronychrony-1.29.1-1.el7.x86_642、配置时间同步服务:启动时间同步服务:# systemctl start chronyd.service配置时间同步源:# vi /etc/chron..._redhuat7 修改时间提前8小时

zoj 3430(ac自动机)-程序员宅基地

题意:给出n个模式串,是以base64编码的,m个目标串,也是base64编码,问每个目标串里有多少种模式串。base64是把普通ASCII字符二进制表示的每6位截断对应一个最大编号到63的字符表可以对应一个字符,也就是每四个字符对应一个普通字符,不够就末尾补零。补两个0是”=”,补四个0是”==”。 题解:先把所有给出的串都先解码为普通的字符串,然后是自动机模板解法。#include

Postgresql报错FATAL: XX000: database files are incompatible with server-程序员宅基地

新建数据库,迁移数据,启动的时候无法启动FATAL: XX000: database files are incompatible with serverDETAIL: The database cluster was initialized with RELSEG_SIZE 131072, but the server was compiled with RELSEG_SIZE 1048576.源数据库131072postgres=> select name,setting from p_database files are incompatible with server

LVS+Keepalived使用总结_当keepalived与lvs连用时,keepalived可以替lvs做哪些工作?-程序员宅基地

一、lvs简介和推荐阅读的资料二、lvs和keepalived的安装三、LVS VS/DR模式搭建四、LVS VS/TUN模式搭建五、LVS VS/NAT模式搭建六、keepalived多种real server健康检测实例七、lvs持久性工作原理和配置八、lvs数据监控九、lvs+keepalived故障排除一、LVS简介和推荐阅读的资料 学习L..._当keepalived与lvs连用时,keepalived可以替lvs做哪些工作?

stm32f105使用12M外部晶振-程序员宅基地

cl:互联型产品,stm32f105/107系列vl:超值型产品,stm32f100系列xl:超高密度产品,stm32f101/103系列ld:低密度产品,FLASH小于64Kmd:中等密度产品,FLASH=64 or 128hd:高密度产品,FLASH大于128STM32F105和107是互联型产品。在system_stm32f10x.c中他们的晶振默认是25

随便推点

ImageLabel 图像数据集制作_imglabel_Monkey_Men的博客-程序员宅基地

数据集收集 协助及方法该压缩包 解压在D:\ 路径下ImageLabel 软件 解压后即可使用工作基本流程Open Dir (打开对应图像文件夹) ->Change Save Dir (修改标注产生xml存储路径为该该文件夹位置 xml_collection中) ->Edit (可以定制自己的标注对应的方框) ->Create RectBox (生成标注框) ->label (修改label信息) ->Save (存储相应的xml信息)next image_imglabel

Ruby on rails 实战圣经:ActiveRecord-程序员宅基地

All problems in computerscience can be solved by another level of indirection(abstraction) - DavidWheeler ...except for the problem of too many layers of indirection. - KevlinHenney’s corollaryActiveR

microsoft sql server management studio问题_加载microsoft sql server management studio express菜单-程序员宅基地

microsoft sql server management studio问题打开数据库时报错,提示应用程序组件中发生了无法处理的异常。如果单击“继续”,应用程序将忽略此错误并尝试继续。但是第一想法是:是不是SQLServer安装时没有使用密钥进行激活,因为之前也出现过没有激活而无法打开sql Server。 不过,后来查找资料之后发现跟之前的问题并不是一样的,针对此类问题的解决办法是:将路径C:\Documentsand Settings\Administrator\Application Da_加载microsoft sql server management studio express菜单时出现问题

postgres预写式日志的内核实现详解-wal记录写入-程序员宅基地

2019独角兽企业重金招聘Python工程师标准>>> ...

libRTMP使用说明-程序员宅基地

名称librtmp − RTMPDump Real-Time Messaging Protocol API库RTMPDump RTMP(librtmp, -lrtmp)简介#include描述实时流协议(Real-TimeMessaging Protocol,RTMP)是用于互联网上传输视音频数据的网络协议。本API提供了支持RTMP, RTMPT,RTMPE, RTMP RTMPS以及以上几种协议的变种(RTMPTE, RTMPTS)协议所需的大部分客户端功能_librtmp

python连接redis数据库_python redis 是否可以先创建连接对象 再连接某个库_张张呀呀的博客-程序员宅基地

python连接redis数据库Python的第三方库初始化并创建连接Python的第三方库pip install redis初始化并创建连接pool = redis.ConnectionPool(host="***", port=***, password='***', db=***)r = redis.Redis(connection_pool=pool)_python redis 是否可以先创建连接对象 再连接某个库

推荐文章

热门文章

相关标签