All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yixan.base.web.aspectj.SystemLogAspectj Maven / Gradle / Ivy

There is a newer version: 3.7.1
Show newest version
package com.yixan.base.web.aspectj;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.yixan.base.common.api.system.model.IUser;
import com.yixan.base.common.api.system.model.SystemLogBean;
import com.yixan.base.common.api.system.service.ISystemLogService;
import com.yixan.base.common.enums.IUserType;
import com.yixan.base.core.exception.ResultCode;
import com.yixan.base.core.exception.ServiceException;
import com.yixan.base.core.result.IResultMessage;
import com.yixan.base.web.utils.UserUtil;
import com.yixan.base.web.utils.WebUtil;
import com.yixan.tools.common.util.DateUtil;
import com.yixan.tools.common.util.StringUtil;
import com.yixan.tools.common.util.VerifyUtil;

/**
 * 系统日志切面
 *
 * @author zhaohuihua
 * @version V1.0 2016年4月26日
 * @deprecated 改为OperateRecordAspectj
 */
@Deprecated
public class SystemLogAspectj {

    public static enum LogLevel {
        ALL, RESPONSE_BODY, ERROR, NONE
    }

    private static final String info = "Request info user=%s\nip=%s | session=%s | %s %s\n%s | %sms";
    private static final String trace = "Encoding %s | ContentType %s | ContentLength %s";

    @Autowired(required = false)
    private ISystemLogService systemLogService;

    /** 系统日志要将哪些日志保存到数据库 **/
    private LogLevel saveToDb = LogLevel.ERROR;

    /** 最近检查Service为空的时间, 为避免系统日志刷屏, 同一类错误1小时只输出一次 **/
    private long lastTimeOfServiceIsNull = 0;
    /** 最近一次保存至数据库发生异常的时间, 为避免系统日志刷屏, 同一类错误1小时只输出一次 **/
    private long lastTimeOfSaveToDbError = 0;

    /** 接口执行多久算超时(超时的级别按ERROR处理)(0为不计算超时) **/
    private int executeTimeout = 0;

    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        long time = System.currentTimeMillis();
        try {
            Object returns = point.proceed();
            save(point, returns, System.currentTimeMillis() - time);
            return returns;
        } catch (Throwable e) {
            save(point, e, System.currentTimeMillis() - time);
            throw e;
        }
    }

    /** 系统日志要将哪些日志保存到数据库 **/
    public void setSaveToDb(LogLevel saveToDb) {
        this.saveToDb = saveToDb;
    }

    /** 接口执行多久算超时(超时的级别按ERROR处理)(0为不计算超时) **/
    public void setExecuteTimeout(int executeTimeout) {
        this.executeTimeout = executeTimeout;
    }

    private void save(ProceedingJoinPoint point, Object returns, Long time) {

        Logger log = LoggerFactory.getLogger(point.getTarget().getClass());
        String sign = point.getSignature().toShortString();

        // 获取相关参数
        WebUtil wu = WebUtil.getInstance();
        HttpServletRequest req = wu.getRequest();
        IUser user = UserUtil.checkLoginUser();
        String qs = req.getQueryString();
        String url = req.getRequestURL().append(qs == null ? "" : "?" + qs).toString();
        String ip = wu.getIpAddress();
        String sid = wu.getSessionId();
        String method = req.getMethod();
        String protocol = req.getProtocol();

        // 获取返回码
        String code = null;
        String msg = null;
        if (returns instanceof IResultMessage) {
            IResultMessage result = (IResultMessage) returns;
            code = result.getCode();
            msg = result.getMessage();
        }

        String text = null;
        if (returns != null) {
            String temp;
            if (returns instanceof CharSequence) {
                temp = returns.toString();
            } else if (returns instanceof Throwable) {
                String m = ((Throwable) returns).getMessage();
                String n = returns.getClass().getSimpleName();
                temp = m == null ? n : n + ": " + m;
            } else {
                temp = JSON.toJSONString(returns);
            }
            // 避免返回字符串过长
            text = StringUtil.ellipsis(temp, 500);
        }

        // 记录请求日志
        if (log.isDebugEnabled()) {
            StringBuilder buffer = new StringBuilder();
            buffer.append("\n");
            buffer.append("/*******************************************************\\");
            buffer.append("\n");
            buffer.append(String.format(info, user, ip, sid, method, url, sign, time));
            if (VerifyUtil.isNotBlank(code) && VerifyUtil.isNotBlank(msg)) {
                buffer.append(" | ").append(code + ":" + msg);
            } else if (VerifyUtil.isNotBlank(code)) {
                buffer.append(" | ").append(code);
            } else if (VerifyUtil.isNotBlank(msg)) {
                buffer.append(" | ").append(msg);
            }

            if (log.isTraceEnabled()) {
                // 请求参数
                StringBuffer params = new StringBuffer();
                for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
                    String k = e.nextElement();
                    String v = StringUtil.ellipsis(req.getParameter(k), 200); // 避免字符串过长
                    params.append(k).append("=").append(v).append(";");
                }
                // 请求头
                StringBuffer headers = new StringBuffer();
                for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
                    String k = e.nextElement();
                    headers.append(k).append("=").append(req.getHeader(k)).append(";");
                }
                String contentType = req.getContentType();
                String encoding = req.getCharacterEncoding();
                long length = req.getContentLength();
                buffer.append("\n");
                buffer.append("Response ").append(text);
                buffer.append("\n");
                buffer.append(String.format(trace, encoding, contentType, length));
                if (params.length() > 0) {
                    buffer.append("\n");
                    buffer.append("Parameters ").append(params);
                }
                if (headers.length() > 0) {
                    buffer.append("\n");
                    buffer.append("Headers ").append(headers);
                }
            }
            buffer.append("\n");
            buffer.append("\\*******************************************************/");
            log.debug(buffer.toString());
        }

        // 计算日志级别
        // 如果返回的是IResultMessage, 就是ResponseBody, 再判断返回码, 如果不成功就是ERROR
        LogLevel level = LogLevel.ALL;
        if (executeTimeout > 0 && time >= executeTimeout) {
            // 超时的级别按ERROR处理
            level = LogLevel.ERROR;
        } else if (returns instanceof Throwable) {
            level = LogLevel.ERROR;
        } else if (returns instanceof IResultMessage) {
            if (ResultCode.SUCCESS.getCode().equals(code)) {
                level = LogLevel.RESPONSE_BODY;
            } else {
                level = LogLevel.ERROR;
            }
        }
        if (level.ordinal() >= saveToDb.ordinal()) {
            if (systemLogService == null) {
                // systemLogService注入失败
                long mills = System.currentTimeMillis();
                if (mills - lastTimeOfServiceIsNull > DateUtil.RATE_HOUR) {
                    lastTimeOfServiceIsNull = mills;
                    log.warn("Can't save access log to db, SystemLogService is null.");
                }
            } else {
                // 构造入库参数
                SystemLogBean bean = new SystemLogBean();
                // 用户信息
                if (user != null) {
                    bean.setUserId(user.getUserId());
                    bean.setUserName(user.getDisplayName());
                    IUserType type = user.getUserType();
                    if (type != null) {
                        bean.setUserType(type.name());
                    }
                }
                // 请求信息
                bean.setIp(ip);
                bean.setRequestMethod(method);
                bean.setRequestProtocol(protocol);
                bean.setRequestUrl(url);
                // 执行信息
                bean.setExecuteMethod(sign);
                bean.setExecuteTime(time);
                // 响应信息
                bean.setReturnCode(code);
                bean.setReturnContent(text);

                try {
                    // 入库
                    systemLogService.create(bean);
                } catch (ServiceException e) {
                    long mills = System.currentTimeMillis();
                    if (mills - lastTimeOfSaveToDbError > DateUtil.RATE_HOUR) {
                        lastTimeOfSaveToDbError = mills;
                        log.warn("Save access log to db error. {}{}", e.toString(), StringUtil.toLogs(bean), e);
                    }
                }
            }
        }

    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy