1. 程式人生 > >《web工程aop實現前臺操作日誌記錄》初稿

《web工程aop實現前臺操作日誌記錄》初稿

寫日誌功能很繁瑣,博主廢了一些時間寫出來分享,用的ssm框架,後期會設定優先順序,避免所有方法都會被記錄到日誌。開始:

1、首先定義一個自定義註解@controllerLog和@serviceLog


package com.hhwy.business.annotation;


import java.lang.annotation.*;
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ControllerLog {
String description()  default "";
}

package com.hhwy.business.annotation;


import java.lang.annotation.*;


@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ServiceLog {
String description()  default "";
}

2、在webapp下找到 plugin-config.xml或者applicationContext.xml(公司專案中用的plugin-config.xml,以此為例)



3、完了之後可以手寫Aspect類

package com.hhwy.business.service.impl;


import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


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


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import com.alibaba.fastjson.JSON;
import com.hhwy.business.annotation.ControllerLog;
import com.hhwy.business.annotation.ServiceLog;
import com.hhwy.business.core.modelutil.ExecutionResult;
import com.hhwy.business.domain.LogException;
import com.hhwy.business.domain.LogMeg;
import com.hhwy.business.service.LogService;
import com.hhwy.framework.util.PlatformTools;
import com.hhwy.sso.client.filter.SessionUtil;


 


@Aspect
@Component
@Scope("prototype")
public  class LogAspect {

    //注入Service用於把日誌儲存資料庫
    @Resource
    private LogService logService;
    //本地異常日誌記錄物件
    private  static  final Logger logger = LoggerFactory.getLogger(LogAspect. class);
 
    //Service層切點
    @Pointcut("@annotation(com.hhwy.business.annotation.ServiceLog)")
    public  void serviceAspect() {
    }
    //Controller層切點
    @Pointcut("@annotation(com.hhwy.business.annotation.ControllerLog)")
    public  void controllerAspect() {
    } 
    //定義id接受資料庫中存放位置的id
String id;
    /**
     * 前置通知 用於攔截Controller層記錄使用者的操作
     *
     * @param joinPoint 切點
     */
    @Around("controllerAspect()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
   
    //讀取session中的使用者
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
   
    //請求的IP
    String ip = request.getRemoteAddr();
    LogMeg log = new LogMeg();
    Object proceed = null;
    try {
    //獲取執行的方法名
    log.setOperateMethod((pjp.getTarget().getClass().getName() + "." + pjp.getSignature().getName() + "()"));
    //獲取呼叫方法的使用者ip
    log.setOperateIp(ip);//ip放入logMeg實體
    //獲取執行的模組(註解中的內容)
    log.setOperateModule(JSON.toJSONString(getControllerMethodDescription(pjp)));
    //獲取訪問者的唯一標識
    log.setVisitorId(SessionUtil.getLoginUserId());
    //獲取使用者名稱
    log.setOperator(SessionUtil.getLoginName());
    //獲取使用者訪問的uri
    log.setURI(request.getRequestURI());  
    //獲取方法執行前時間
       Date date=new Date();
    DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String startTime=format.format(date);    
    log.setStartTime(startTime);
    this.id = PlatformTools.getID();
    //aop環繞環繞通知執行的原方法
    proceed = pjp.proceed();
    //提取controller中ExecutionResult的屬性
    ExecutionResult result = (ExecutionResult) proceed;
    log.setOperateResult(result.getCode());
    log.setDetail(result.getMsg());
    //獲取方法呼叫結束時間
    Date date2=new Date();
     DateFormat format2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String endTime =format2.format(date2);
    log.setEndTime(endTime);
    log.setId(this.id);
    System.out.println("儲存前:^^^^^^^^^^^^^^^^^^^^^"+id);
    logService.saveLog(log);
    System.out.println("儲存後^^^^^^^^^^^^^^^^^^^^^"+id);
    System.out.println(this);
    return proceed;
    }  catch (Exception e) {
    e.printStackTrace();
    //記錄本地異常日誌
    logger.error("==環繞通知異常==");
    logger.error("異常資訊:{}", e.getMessage());
    return null;
    }
    }
       
    /**
     * 異常通知 用於攔截service層記錄異常日誌
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
    public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //讀取session中的使用者
        SessionUtil.getLoginUserName();
        //獲取請求ip       
        String ip = request.getRemoteAddr();
        LogException logException  =  new LogException();
        try {
               /*==========資料庫日誌=========*/
            logException.setExceptionCode(e.getClass().getName());
            logException.setExceptionMessage(e.getMessage());
            logException.setExceptionMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
            System.out.println("儲存前:#################################"+this.id);
            System.out.println(this);
            logException.setLogOperateId(this.id);
            System.out.println(logException.getLogOperateId()+"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
            logException.setMethodDescription(getServiceMthodDescription(joinPoint));
            //儲存資料庫
            logService.saveLogException(logException);
            System.out.println("儲存後:#################################"+this.id);
        }  catch (Exception exception) {
            //記錄本地異常日誌
        exception.printStackTrace();
            logger.error("==serivce通知異常==");
            logger.error("異常資訊:{}", e.getMessage());
        }
         /*==========記錄本地異常日誌==========*/
       logger.error("異常方法:{}異常程式碼:{}異常資訊:{}引數:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage());
 
    }
 
 
    /**
     * 獲取註解中對方法的描述資訊 用於service層註解
     *
     * @param joinPoint 切點
     * @return 方法描述
     * @throws Exception
     */
    public  static String getServiceMthodDescription(JoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(ServiceLog. class).description();
                    break;
                }
            }
        }
        return description;
    }
 
    /**
     * 獲取註解中對方法的描述資訊 用於Controller層註解
     *
     * @param joinPoint 切點
     * @return 方法描述
     * @throws Exception
     */
    public  static String getControllerMethodDescription(ProceedingJoinPoint pjp)  throws Exception {
        String targetName = pjp.getTarget().getClass().getName();
        String methodName = pjp.getSignature().getName();
        Object[] arguments = pjp.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(ControllerLog. class).description();
                    break;
                }
            }
        }
        return description;
    }
}

4、接下來寫一個service介面及實現類,用來儲存獲取到的檢測資訊

package com.hhwy.business.service.impl;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import com.hhwy.business.annotation.ServiceLog;
import com.hhwy.business.domain.LogException;
import com.hhwy.business.domain.LogMeg;
import com.hhwy.business.domain.LogMessageDetail;
import com.hhwy.business.domain.LogVo;
import com.hhwy.business.service.LogService;
import com.hhwy.framework.persistent.DAO;
import com.hhwy.framework.persistent.QueryResult;


@Component
public class LogServiceImpl implements LogService{
@Autowired
DAO<?> dao;


/**
* 儲存日誌資訊
*/
public void saveLog(LogMeg lmg){
dao.save(lmg);
}
public void saveLogException(LogException logException){
dao.save(logException);
}
/**
* 分頁查詢log資訊表
*/
@ServiceLog(description = "查詢日誌service")
public QueryResult<LogMeg> getLogMessageByPage(LogVo logVo){
QueryResult<LogMeg> queryResult = new QueryResult<LogMeg>();
long total = getLogCount(logVo);
//int a=1/0;
List<LogMeg> data = getLogMessage(logVo);
queryResult.setTotal(total);
queryResult.setData(data);
return queryResult;
}
public Integer getLogCount(LogVo logVo){
Object result = dao.getOneBySQL("logSpace.sql.projectsSize",logVo);
int total = result == null ? 0 : Integer.valueOf(result.toString());
return total;
}
@SuppressWarnings("unchecked")
public List<LogMeg> getLogMessage(LogVo logVo){
if (logVo == null) {
logVo = new LogVo();
}
List<LogMeg> logMessage = (List<LogMeg>) dao.getBySql("logSpace.sql.logPage", logVo);
return logMessage;
}
/**
* 通過ID查詢所有日誌記錄詳情
*/
public LogMessageDetail getLogMessage(String id){
LogMessageDetail logMessageDetail = new LogMessageDetail();
logMessageDetail.setLogMeg(getLogById(id));//a4e55ef84bda4d09a809a2561e51770d
LogException logException = new LogException();
logException.setLogOperateId(id);//a4e55ef84bda4d09a809a2561e51770d
logMessageDetail.setLogException(getLogExceptionById(logException.getLogOperateId()));
return logMessageDetail;

}
/**
* 通過id獲取log詳細資訊
*/
public LogMeg getLogById(String id){
LogMeg logMeg =  dao.findById(id, LogMeg.class);
return logMeg;
}
/**
* 通過id獲取logException詳細資訊
*/
public LogException getLogExceptionById(String id) {
LogException logException = (LogException) dao.getOneBySQL("logSpace.sql.logExceptionPageById", id);
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+logException+id);
return logException;
}

}

這過程中用寫了2個實體類(logException記錄異常資訊,logMeg記錄執行正常資訊)1個vo (需要傳遞引數的實體類)1個detail(需要顯示到前臺的類)


package com.hhwy.business.domain;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;


import com.hhwy.framework.persistent.entity.Domain;
@Entity(name="LogException")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name="log_exception")
public class LogException extends Domain{


/**
* serialVersionUID
* @return  the serialVersionUID
* @since   1.0.0
*/
private static final long serialVersionUID = 1L;
//表log_operate的id外來鍵
@Column(name="log_operate_id", length=32)
private String logOperateId;
//異常程式碼
@Column(name="exception_code", length=512)
private String exceptionCode;
//異常資訊
@Column(name="exception_message", length=512)
private String exceptionMessage;
//異常方法
@Column(name="exception_method", length=100)
private String exceptionMethod;
//異常方法描述
@Column(name="method_description", length=100)
private String methodDescription;
public String getMethodDescription() {
return methodDescription;
}
public void setMethodDescription(String methodDescription) {
this.methodDescription = methodDescription;
}
public String getLogOperateId() {
return logOperateId;
}
public void setLogOperateId(String logOperateId) {
this.logOperateId = logOperateId;
}
public String getExceptionCode() {
return exceptionCode;
}
public void setExceptionCode(String exceptionCode) {
this.exceptionCode = exceptionCode;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public String getExceptionMethod() {
return exceptionMethod;
}
public void setExceptionMethod(String exceptionMethod) {
this.exceptionMethod = exceptionMethod;
}
public static long getSerialversionuid() {
return serialVersionUID;
}


}

《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》

package com.hhwy.business.domain;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;


import com.fasterxml.jackson.annotation.JsonFormat;
import com.hhwy.framework.persistent.entity.Domain;


@Entity(name="LogMeg")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name="log_operate")
public class LogMeg extends Domain {
/**
* serialVersionUID
* @return  the serialVersionUID
* @since   1.0.0
*/
private static final long serialVersionUID = 1L;
//記錄操作人ID
@Column(name="visitor_id", length=32)
private String visitorId;
//記錄操作人的ip
@Column(name="operate_ip", length=32)
private String operateIp;
//記錄操作人的使用者名稱
@Column(name="operator", length=32)
private String operator;
//記錄操作模組
@Column(name="operate_module", length=32)
private String operateModule;
//記錄操作開始時間
@Column(name="start_time", length=32)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private String startTime;
//記錄模組操作的方法
@Column(name="operate_method", length=256)
private String operateMethod;
//記錄操作結果
@Column(name="operate_result", length=32)
private String operateResult;
//記錄操作結束時間
@Column(name="end_time", length=100)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private String endTime;
//記錄操作詳情
@Column(name="detail", length=100)
private String detail;
//執行的uri
@Column(name="uri", length=100)
private String URI;
public String getURI() {
return URI;
}
public void setURI(String uRI) {
URI = uRI;
}
public String getOperateIp() {
return operateIp;
}
public void setOperateIp(String operateIp) {
this.operateIp = operateIp;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getOperateModule() {
return operateModule;
}
public void setOperateModule(String operateModule) {
this.operateModule = operateModule;
}
public String getOperateMethod() {
return operateMethod;
}
public void setOperateMethod(String parammaps) {
this.operateMethod = parammaps;
}

public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getVisitorId() {
return visitorId;
}
public void setVisitorId(String visitorId) {
this.visitorId = visitorId;
}
public String getOperateResult() {
return operateResult;
}
public void setOperateResult(String operateResult) {
this.operateResult = operateResult;
}
}

《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》

package com.hhwy.business.domain;


import com.hhwy.business.core.modelutil.PagingProperty;


public class LogVo extends PagingProperty{
//記錄操作模組
private String operateModule;
//記錄模組操作的方法
private String operateMethod;
//記錄操作結果
private String operateResult;
//記錄產生詳情
private String detail;

public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getOperateModule() {
return operateModule;
}
public void setOperateModule(String operateModule) {
this.operateModule = operateModule;
}
public String getOperateMethod() {
return operateMethod;
}
public void setOperateMethod(String operateMethod) {
this.operateMethod = operateMethod;
}
public String getOperateResult() {
return operateResult;
}
public void setOperateResult(String operateResult) {
this.operateResult = operateResult;
}
}

《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》《》

package com.hhwy.business.domain;


public class LogMessageDetail{

//封裝了兩個實體類作為引數
private LogMeg logMeg;
private LogException logException;
public LogMeg getLogMeg() {
return logMeg;
}
public void setLogMeg(LogMeg logMeg) {
this.logMeg = logMeg;
}
public LogException getLogException() {
return logException;
}
public void setLogException(LogException logException) {
this.logException = logException;
}
}

5、資料庫同樣我建立了兩張表、分別儲存logMeg和logException

log_exception表


log_operate表:


6、那麼接下來的工作都結束了,可以檢測我們的成果

1、頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<jsp:include page="/plugins/business-core/static/headers/base.jsp"></jsp:include>
</head>
<body id="consVue" v-cloak style="height: 100%">
<mk-top-bottom height="100%" top_height="auto">
<mk-search-panel slot="top" deployable="false" title="Test888888888888">
</mk-search-panel> 
<mk-panel title="日誌資訊顯示" line="true" v-cloak slot="bottom" height="100%">
<div slot="buttons" class="pull-right " style="text-align: right" v-cloak>
<su-button class="btn-operator" s-type="default" labeled="true" v-on:click="detail">檢視詳情</su-button>
</div>
<div class="col-xs-12" style="height: 500px">
<table id="consGrid" style="height: 300px"></table>
</div>
</mk-panel> 

</mk-top-bottom>
<script type="text/javascript">
var basePath = '${Config.baseURL}';
//對應 js
var consVue = new Vue({
el : '#consVue',
data : {
params : {
LogVo : {
operateModule : null,
operateMethod : null,
operateResult : null,
detail :null
}
},
editable:true
},
ready : function() {
//列表資料載入
$('#consGrid').datagrid({
url: basePath + 'business/LogController/LogPage',
   width:"100%",
   height:"300px",
   pagination: true,
   method: 'post', 
singleSelect:true,
   queryParams:this.params,
   rownumbers: true,
   pagination: true,
   nowrap: false,
   fitColumns:true,

   columns:[[  
  {field:'visitorId',title:'使用者名稱',width:100},
          {field:'operateModule',title:'操作模組',width:100},   
          {field:'operateMethod',title:'操作方法',width:100},   
          {field:'operateResult',title:'操作結果',width:100},   
          {field:'detail', title:'詳情',width:100}   
      ]],

   pageSize: 10,
   pageList: [10, 20, 50, 100, 150, 200],
   rowStyler:function(idx,row){
       return "height:35px;font-size:12px;";
   }
   }); 
},
methods : {
detail : function(id) {
var row = $('#consGrid').datagrid('getSelected');
$.ajax({
    type:"GET",
    url: 'detail.jsp',
    async:false,
    data:null,
    success:function(msg){
        if (msg) {//根據返回值進行跳轉
            window.location.href = '${Config.baseURL}view/business/archives/scconsumerinfo/detail?id='+row.id;
        }
    }

});
}
}
} );
</script>
</body>
</html>

詳情頁detail

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<jsp:include page="/plugins/business-core/static/headers/base.jsp"></jsp:include>
<style type="text/css">
.datagrid-row-selected{
background-color: #eeeeee;
color:#000000;
}
</style>
</head>
<body id="logDetail" v-cloak>
<mk-form-panel title="日誌資訊詳情" label_width="140px">
    <mk-form-row>
        <mk-form-col label="使用者ID">
            <su-textbox type="text"  placeholder="" :data.sync="params.logMeg.visitorId"  disabled></su-textbox>
        </mk-form-col>
         <mk-form-col label="操作人" >
            <su-textbox name="bdz" id="bdz61549_id"  :data.sync="params.logMeg.operator" disabled></su-textbox>
        </mk-form-col>
        <mk-form-col label="操作人Ip">
            <su-textbox name="bdz" id="bdz61549_id"  :data.sync="params.logMeg.operateIp" disabled></su-textbox>
        </mk-form-col>
    </mk-form-row>
    <mk-form-row>
        <mk-form-col label="操作模組" >
            <su-textbox name="bdz" id="bdz61549_id"  :data.sync="params.logMeg.operateModule"  disabled></su-textbox>
        </mk-form-col>


        <mk-form-col label="操作方法" >
            <su-textbox type="text"  placeholder="" :data.sync="params.logMeg.operateMethod" disabled></su-textbox>
        </mk-form-col>
<mk-form-col   label="起始時間" >
            <su-textbox type="text"  placeholder="" :data.sync="params.logMeg.startTime" disabled></su-textbox>
        </mk-form-col>
    </mk-form-row>
    
    <mk-form-row>
       <mk-form-col   label="結束時間" >
            <su-textbox type="text"  placeholder="" :data.sync="params.logMeg.endTime" disabled></su-textbox>
        </mk-form-col>
        <mk-form-col   label="耗時"  >
            <su-textbox type="text" rows="3" rols="10" name="bdz" id="bd_id"  :data.sync="haoshi" disabled></su-textbox>
       </mk-form-col>
         <mk-form-col label="操作結果" >
            <su-textbox name="bdz" id="bdz61549_id"  :data.sync="params.logMeg.operateResult" disabled></su-textbox>
        </mk-form-col>
     </mk-form-row>
     <mk-form-row height="90px">
    <mk-form-col  colspan="3" label="日誌詳情"  >
            <su-textbox type="textarea" rows="3" rols="10" name="bdz" id="bdz61549_id"  :data.sync="params.logMeg.detail" disabled></su-textbox>
       </mk-form-col>
      </mk-form-row>
      <mk-form-row>
       <mk-form-col   label="異常程式碼" >
            <su-textbox type="text"  placeholder="" :data.sync="params.logException.exceptionCode" disabled></su-textbox>
        </mk-form-col>
        <mk-form-col   label="異常資訊"  >
            <su-textbox type="text" rows="3" rols="10" name="bdz" id="bdz61549_id"  :data.sync="params.logException.exceptionMessage" disabled></su-textbox>
       </mk-form-col>
         <mk-form-col label="異常方法" >
            <su-textbox name="bdz" id="bdz61549_id"  :data.sync="params.logException.exceptionMethod" disabled></su-textbox>
        </mk-form-col>
     </mk-form-row>
     <mk-form-row height="170px">
    <mk-form-col  colspan="3" label="異常描述"  >
            <su-textbox type="textarea" rows="7" rols="10" name="bdz" id="bdz61549_id"  :data.sync="params.logException.methodDescription" disabled></su-textbox>
       </mk-form-col>
      </mk-form-row>
</mk-form-panel>


<script type="text/javascript">
var basePath = '${Config.baseURL}';
//對應 js
var id='${param.id}';
var logDetail=new Vue({
el: '#logDetail',
data: {
params:{
logMeg:{visitorId:null,operateIp:null,operator:null,operateModule:null,operateMethod:null,operateResult:null,detail:null,
startTime:null,endTime:null},
logException:{exceptionCode:null,exceptionMessage:null,exceptionMethod:null,methodDescription:null}
},
haoshi:null
},
ready : function() {
var me=this;
$.ajax({
type:'GET',
url:basePath + 'LogController/getLogMessage/'+id,
data: String, 
           contentType: "application/json;charset=utf-8", 
           //dataType: "json", 
           async: false,//同步    
error: function () {//請求失敗處理函式
    alert('請求失敗');
   },
success:function(data){
me.params=data.data;
}    
})
}
});
</script>
</body>
</html>

用到的controller類

package com.hhwy.business.controller;




import javax.servlet.http.HttpServletRequest;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import com.hhwy.business.annotation.ControllerLog;
import com.hhwy.business.core.modelutil.ExecutionResult;
import com.hhwy.business.core.modelutil.ReturnCode;
import com.hhwy.business.domain.LogMeg;
import com.hhwy.business.domain.LogMessageDetail;
import com.hhwy.business.domain.LogVo;
//import com.hhwy.business.logUtil.StaticLogUtil;
import com.hhwy.business.service.LogService;
import com.hhwy.framework.persistent.QueryResult;






@RestController
@RequestMapping("/LogController")
public class LogController {
@Autowired
LogService logService;
public static final Logger log = LoggerFactory.getLogger(LogMeg.class);
/**
* 通過傳入實體lmg,增加日誌資訊
* saveLogMessage(描述這個方法的作用)<br/>
* @param lmg
* @return 
* Object
* @exception 
* @since  1.0.0
*/
@RequestMapping(value = "saveLogMessage", method = RequestMethod.GET)
public Object saveLogMessage(@PathVariable LogMeg lmg){
ExecutionResult result = new ExecutionResult();
try {
   logService.saveLog(lmg);
result.setCode(ReturnCode.RES_SUCCESS);//設定返回結果編碼:成功
result.setFlag(true);//設定是否成功標識
result.setMsg("儲存成功!");//設定返回訊息,根據實際情況修改
} catch (Exception e) {
log.error("儲存失敗!",e);//記錄異常日誌,根據實際情況修改
result.setCode(ReturnCode.RES_FAILED);//設定返回結果編碼:失敗
result.setFlag(false);//設定是否成功標識
result.setData(null);//設定返回結果為空
result.setMsg("儲存失敗!");//設定返回訊息,根據實際情況修改
return result;
}
return result;
}
/**
* 獲取日誌列表,分頁顯示
* getLogByPage(描述這個方法的作用)<br/>
* @param logMeg
* @return
* @throws Exception 
* Object
* @exception 
* @since  1.0.0
*/
@ControllerLog(description = "日誌新增操作")
@RequestMapping(value = "/LogPage", method = RequestMethod.POST)
public Object getLogByPage(HttpServletRequest req, @RequestBody(required=false) LogVo logVo){
ExecutionResult result = new ExecutionResult();
System.out.println("controller的地址:"+ this);
        try {
        QueryResult<LogMeg> queryResult = logService.getLogMessageByPage(logVo);
    result.setTotal(queryResult.getTotal());//設定資料總條數
    result.setRows(queryResult.getRows() == null ? queryResult.getData() : queryResult.getRows());//設定資料列表
            result.setCode(ReturnCode.RES_SUCCESS);     //設定返回結果編碼:成功
            result.setFlag(true);                       //設定是否成功標識
            result.setMsg("查詢成功!");                 //設定返回訊息,根據實際情況修改
        } catch (Exception e) {
            log.error("查詢失敗!",e);                       //記錄異常日誌,根據實際情況修改
            result.setCode(ReturnCode.RES_FAILED);      //設定返回結果編碼:失敗
            result.setFlag(false);                      //設定是否成功標識
            result.setData(null);                       //設定返回結果為空
            result.setMsg("查詢失敗!");                 //設定返回訊息,根據實際情況修改
        }
        return result;
}

       
    
@RequestMapping(value = "/getLogMessage/{id}", method = RequestMethod.GET)
    public Object getLogMessage(@PathVariable String id) {
        ExecutionResult result = new ExecutionResult();
        try {
        LogMessageDetail logMessageDetaileg = logService.getLogMessage(id);
          
            result.setCode(ReturnCode.RES_SUCCESS);     //設定返回結果編碼:成功
            result.setFlag(true);                       //設定是否成功標識
            result.setData(logMessageDetaileg);                //設定實體
            result.setMsg("查詢成功!");                 //設定返回訊息,根據實際情況修改
        } catch (Exception e) {
            log.error("查詢失敗!",e);                       //記錄異常日誌,根據實際情況修改
            result.setCode(ReturnCode.RES_FAILED);      //設定返回結果編碼:失敗
            result.setFlag(false);                      //設定是否成功標識
            result.setData(null);                       //設定返回結果為空
            result.setMsg("查詢失敗!");                 //設定返回訊息,根據實際情況修改
            return result;
        }
        return result;
    }   
}

6、大功告成

使用過程中只需要在這兩個地方加上註解就可以了

controller層


service層加


ok,可以了

相關推薦

web工程aop實現前臺操作日誌記錄初稿

寫日誌功能很繁瑣,博主廢了一些時間寫出來分享,用的ssm框架,後期會設定優先順序,避免所有方法都會被記錄到日誌。開始: 1、首先定義一個自定義註解@controllerLog和@serviceLog package com.hhwy.business.annotation

springboot—spring aop 實現系統操作日誌記錄存儲到數據庫

work prop 請求 pack spa 成功 方法 代碼 shu 原文:https://www.jianshu.com/p/d0bbdf1974bd 采用方案: 使用spring 的 aop 技術切到自定義註解上,針對不同註解標誌進行參數解析,記錄日誌

spring aop 實現使用者操作日誌記錄功能

首先寫好一個工具類 LogAspect.java package com.yangjf.commons; import java.lang.reflect.Method; import java.util.Date; import org.aspectj.lang.Join

Spring Aop實現使用者操作日誌記錄

package com.jixi.controller; import com.jixi.pojo.Log; import com.jixi.pojo.User; import com.jixi.service.ILogService; import com.jixi.service.IUserServic

使用Spring AOP自定義註解方式實現使用者操作日誌記錄

1,開發環境 作業系統:Windows 7 JDK:1.8.0_161 Eclipse:Mars.2 Release (4.5.2) 2,自定義註解類UserLog @Target({ElementType.PARAMETER, ElementType.METHOD}) @R

Springboot 如何使用AOP同時織入多個切面?實現使用者 操作日誌記錄功能

首先匯入AOP的pom <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-sta

spring配置日誌切面,實現系統操作日誌記錄

//做系統是經常會遇到的情況之一,對系統操作日誌存表記錄 下面給出下例子 需要注意的是,日誌通常資料量會很大,建議已每個人月一張表,或者其他方式分表 例如:logs_2012_1             logs_2012_2             logs_2012_

利用SpringMVC的AOP實現後臺系統的操作日誌記錄

最近在專案中要求把後臺的一些關鍵操作記錄下來,想了好半天能想到的也就那兩三種方式,要麼就是寫一個攔截器,然後再web.xml裡面進行配置,要麼就是就是在每個需要記錄操作日誌的程式碼裡面進行攔截,最後我選擇了第三種,也就是基於AOP的攔截,用這種方式,只需要在需記

整合springboot+mvc+mybatis(通用mapper)+druid+jsp+bootstrap實現許可權管理檔案上傳下載多資料來源切換操作日誌記錄等功能

花了兩週,學習了下springboot,然後做個小東西練練手.專案基於jdk1.8+maven整合了springboot+mvc+mybatis(通用mapper)+druid+jsp+bootstrap等技術,springboot+Listener(監聽器),Filter

利用Java Annotation 和 Spring AOP實現在Controller層面的操作日誌記錄

Annotation,Spring,AOP之類的概念這裡就不在介紹了,網上的相關知識一搜在大堆,而且也是各大公司面試之必考內容。目前AOP技術的應用場景中應該很大一部分是用來實現操作日誌記錄的,由於每個公司幾乎都有自己的開發框架,而且很多框架都對CRUD之類的操作進行了高度

springboot AOP全局攔截日誌記錄

quest com info throws ret https log element aspect @Aspect@Component@Slf4jpublic class WebLogAspect { @Pointcut("execution(public * co

springmvc+log4j操作日誌記錄,詳細配置

需要匯入包:  log包:log4j-12.17.jar 第一步:web.xml配置 <!-- log4j配置,檔案路徑,因為是跟隨專案啟動 --> <context-param> <param-name>

從壹開始前後端分離 [.netCore 不定期更新 ] 三十五║ 完美實現全域性異常日誌記錄

緣起 哈嘍我是不定期更新的日常,昨天群裡小夥伴問到了記錄日誌,當然,以前我也挖過這個坑,後來一直沒有來得及填上,也想著 swagger 一直又有錯誤資訊展示的功能,就遲遲沒有新增這個功能,不過昨天夜裡想了想,還是需要增加上,旨在提高框架的高效性。不定期日常就直接上程式碼了,我有一個小想法,就是希望大家有好的

IntelliJ IDEA2017創建web工程實現遠程部署tomca【轉載】

ica 磁盤 int 創建 eclipse 原來 nag 應用 tel [IntelliJ IDEA2017創建web工程並實現遠程部署tomcat] 作者:https://segmentfault.com/a/1190000012762629 5.將應用打成war包 步驟

laravel 利用中介軟體進行操作日誌記錄

利用中介軟體進行操作日誌記錄過程: 1、建立中介軟體 php artisan make:middleware AdminOperationLog 2、生成了檔案./app/Http/Middleware/AdminOperationLog.php 程

Springboot 自定義註解 AOP切面獲取操作日誌

編碼思想: 新增和修改資料,記錄使用者操作資訊(建立人,修改人) ,然後每個模組打算根據操作資料的主鍵id關聯日誌表查詢操作人資訊;需要宣告每個模組名稱及操作方法(constant包中便是宣告的模組和操作方法列舉) 檔案目錄: 1. build.gradle引入jar

SpringBoot 中的aop配置,完成日誌記錄功能

第一步:在pom.xml下新增依賴 因為springboot已經新增過日誌記錄功能的依賴 <!-- 核心模組,包括自動配置支援、日誌支援 --> <dependency> <groupId>org.s

PHP記錄使用者操作日誌記錄

<?php header("Content-type: text/html; charset=utf-8"); error_reporting(0);//關閉所有的錯誤資訊,不會顯示,如果

全域性異常處理器實現系統異常日誌記錄到資料庫

一、需求描述: 每次系統出現異常(有系統異常,也有業務功能的異常)都需要讓運維拉生產上的日誌檔案,檢視哪個地方出問題了,根據列印的log日誌定位問題點以及原因,比較浪費時間。為了解決這個問題,就想到:當系統出現異常時,將異常資訊記錄到資料庫中,然後以簡訊或郵件的形式通知管理

Spring Boot 2.X(八):Spring AOP 實現簡單的日誌切面

AOP 1.什麼是 AOP ? AOP 的全稱為 Aspect Oriented Programming,譯為面向切面程式設計,是通過預編譯方式和執行期動態代理實現核心業務邏輯之外的橫切行為的統一維護的一種技術。AOP 是面向物件程式設計(OOP)的補充和擴充套件。 利用 AOP 可以對業務邏輯各部分進行隔離