1. ホーム
  2. Java

Javaログ取得手順

2022-02-25 09:57:31
<パス

プロジェクトアドレス :https://gitee.com/Selegant/logs-demo.git

説明

システムログは日々の管理やメンテナンスに便利なものですが、ログを取る際に様々な問題が発生することがあります。

  1. ロギングの不規則性
  2. ログ取得の反復性
  3. ログ記録の分類が難しい

現在、ロギングには主に次の3つの分野があります。

  1. リクエストの受信、送信パラメータ
  2. 業務について
  3. 例外日報の印刷

解決方法

1. リクエストの送信と受信のパラメータを記録する

送信と受信の参照をログに記録することは、ログの醍醐味の一つです。ここでは、各リクエストをログに記録する必要があるため、繰り返しがあり、受信と送信の参照の両方でSpring AOPを使って完全に行うことが可能です。

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation;
import org.springframework.stereotype;
import org.springframework.web.context.request;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Web layer logging facet
 */
@Aspect // Use @Aspect annotation here to set up AOP
@Order(5) //the smaller the value, the more it is loaded first
@Component
public class WebLogAspect {

    private Logger logger = Logger.getLogger(getClass());

    ThreadLocal<Long> startTime = new ThreadLocal<>();
	
	// here @Pointcut set the cutpoint can be set to the Controller layer address
    @Pointcut("execute(public * com.training.. *. *Controller(...)) ")
    public void webLog(){}

	//@Before means execute before the cutpoint method, that is, execute before the Controller layer method execution, here you can get some information about the method through JoinPoint, where you can also modify the value of the parameter
    
	//@Before() is set in parentheses is the name of the cutpoint method
	@Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());

        // Receive the request, record the content of the request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // Log the request content
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + ". " + joinPoint.getSignature().getName());
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs())));

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // Finish processing the request and return the content
        logger.info("RESPONSE : " + ret);
        logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
    }

}


2. 操作ログを記録する

システムに関わる追加、削除、変更、業務操作が多いでしょうから、その操作の入力を記録する必要がありますが、ここでは操作の種類、あるいは業務名を記録することも可能です。しかし、操作を記録する前に、ログのベースとなる部分を構築する必要があります。

ログオブジェクト

import java.util;

/**
 * Operation log
 */
public class OperationLog extends Base {

    private static final long serialVersionUID = 1L;

    /**
     * Log type
     */
    private String logtype;
    /**
     * Log name
     */
    private String logname;
    /**
     * user id
     */
    private Integer userid;
    /**
     * Class name
     */
    private String classname;
    /**
     * Method name
     */
    private String method;
    /**
     * Creation time
     */
    private Date createtime;
    /**
     * Whether it was successful or not
     */private
    private String succeed;
    /**
     * Remarks
     */
    private String message;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLogtype() {
        return logtype;
    }

    public void setLogtype(String logtype) {
        this.logtype = logtype;
    }

    public String getLogname() {
        return logname;
    }

    public void setLogname(String logname) {
        this.logname = logname;
    }

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getClassname() {
        return classname;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    public String getSucceed() {
        return succeed;
    }

    public void setSucceed(String succeed) {
        this.success = succeed;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}


import com.stylefeng.guns.common.constant.state.LogSucceed;
import com.stylefeng.guns.common.constant.state.LogType;
import com.stylefeng.guns.common.persistence.model.LoginLog;
import com.stylefeng.guns.common.persistence.model.OperationLog;

import java.util;

/**
 * Log object creation factory
 Date; /* */
public class LogFactory {

    /**
     * Create operation logs
     */
    public static OperationLog createOperationLog(LogType logType, Integer userId, String bussinessName, String clazzName, String methodName, String msg, LogSucceed succeed) {
        OperationLog operationLog = new OperationLog();
        operationLog.setLogtype(logType.getMessage());
        operationLog.setLogname(bussinessName);
        operationLog.setUserid(userId);
        operationLog.setClassname(clazzName);
        operationLog.setMethod(methodName);
        operationLog.setCreatetime(new Date());
        operationLog.setSucceed(proceed.getMessage());
        operationLog.setMessage(msg);
        return operationLog;
    }

    /**
     * Create a login log
     */
    public static LoginLog createLoginLog(LogType logType, Integer userId, String msg,String ip) {
        LoginLog loginLog = new LoginLog();
        loginLog.setLogname(logType.getMessage());
        loginLog.setUserid(userId);
        loginLog.setCreatetime(new Date());
        loginLog.setSucceed(LogSucceed.SUCCESS.getMessage());
        loginLog.setIp(ip);
        loginLog.setMessage(msg);
        return loginLog;
    }
}


ログオブジェクト作成ファクトリー

import com.stylefeng.guns.common.constant.state.LogSucceed;
import com.stylefeng.guns.common.constant.state.LogType;
import com.stylefeng.guns.common.persistence.dao.LoginLogMapper;
import com.stylefeng.guns.common.persistence.dao.OperationLogMapper;
import com.stylefeng.guns.common.persistence.model.LoginLog;
import com.stylefeng.guns.common.persistence.model.OperationLog;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.util;
import com.stylefeng.guns.core.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TimerTask;

/**
 * Logging operation task creation factory
 */
public class LogTaskFactory {

    private static Logger logger = LoggerFactory.getLogger(LogManager.class);
	//LoginLogMapper log login logging
    private static LoginLogMapper loginLogMapper = SpringContextHolder.getBean(LoginLogMapper.class);
	//OperationLogMapper logs the operation log	    
	private static OperationLogMapper operationLogMapper = SpringContextHolder.getBean(OperationLogMapper.class);

    public static TimerTask loginLog(final Integer userId, final String ip) {
        return new TimerTask() {
            @Override
            public void run() {
                try {
                    LoginLog loginLog = LogFactory.createLoginLog(LogType.LOGIN, userId, null, ip);
                    loginLogMapper.insert(loginLog);
                } catch (Exception e) {
                    logger.error("Exception creating login log! ", e);
                }
            }
        };
    }

    public static TimerTask loginLog(final String username, final String msg, final String ip) {
        return new TimerTask() {
            @Override
            public void run() {
                LoginLog loginLog = LogFactory.createLoginLog(
                        LogType.LOGIN_FAIL, null, "Account:" + username + "," + msg, ip);
                try {
                    loginLogMapper.insert(loginLog);
                } catch (Exception e) {
                    logger.error("Failed to create login exception! ", e);
                }
            }
        };
    }

    public static TimerTask exitLog(final Integer userId, final String ip) {
        return new TimerTask() {
            @Override
            public void run() {
                LoginLog loginLog = LogFactory.createLoginLog(LogType.EXIT, userId, null,ip);
                try {
                    loginLogMapper.insert(loginLog);
                } catch (Exception e) {
                    logger.error("Create exit log exception! ", e);
                }
            }
        };
    }

    public static TimerTask bussinessLog(final Integer userId, final String bussinessName, final String clazzName, final String methodName, final String msg) {
        return new TimerTask() {
            @Override
            public void run() {
                OperationLog operationLog = LogFactory.createOperationLog(
                        LogType.BUSINESS, userId, bussinessName, clazzName, methodName, msg, LogSucceed.SUCCESS);
                try {
                    operationLogMapper.insert(operationLog);
                } catch (Exception e) {
                    logger.error("Exception creating business log! ", e);
                }
            }
        };
    }

    public static TimerTask exceptionLog(final Integer userId, final Exception exception) {
        return new TimerTask() {
            @Override
            public void run() {
                String msg = ToolUtil.getExceptionMsg(exception);
                OperationLog operationLog = LogFactory.createOperationLog(
                        LogType.EXCEPTION, userId, "", null, null, msg, LogSucceed.FAIL);
                try {
                    operationLogMapper.insert(operationLog);
                } catch (Exception e) {
                    logger.error("Create exception log exception! ", e);
                }
            }
        };
    }
}



ログタスク作成ファクトリー

<ブロッククオート

ロギングタスクの作成ファクトリーの目的は、データベースにログレコードを保存することである

import java.lang.annotation.*;

/**
 * Mark the methods that need to do business logging
 */
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface BussinessLog {

    /**
     * The name of the business, e.g.: "ModifyMenu"
     */
    String value() default "";

    /**
     * The unique identifier of the entity being modified, e.g.: "id" for the menu entity;
     */
    String key() default "id";

    /**
     * Dictionary(used to find the Chinese name of the key and the Chinese name of the field)
     */
    String dict() default "SystemDict";
}

import com.stylefeng.guns.common.annotion.log.BussinessLog;
import com.stylefeng.guns.common.constant.dictmap.base.AbstractDictMap;
import com.stylefeng.guns.common.constant.dictmap.factory.DictMapFactory;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.log.factory.LogTaskFactory;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.core.util.Contrast;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang;
import org.aspectj.lang.annotation;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect;
import java.util.Map;

/**
 * Logging
 */
@Aspect
@Component
public class LogAop {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut(value = "@annotation(com.stylefeng.guns.common.annotion.log.BussinessLog)")
    public void cutService() {
    }

    @Around("cutService()")
    public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {

        //Execute the business first
        Object result = point.proceed();

        try {
            handle(point);
        } catch (Exception e) {
            log.error("Logging error! ", e);
        }

        return result;
    }

    private void handle(ProceedingJoinPoint point) throws Exception {

        //Get the name of the intercepted method
        Signature sig = point.getSignature();
        MethodSignature msig = null;
        if (! (sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("This annotation can only be used for methods");
        }
        msig = (MethodSignature) sig;
        Object target = point.getTarget();
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        String methodName = currentMethod.getName();

        // If the current user is not logged in, no logging is done
        ShiroUser user = ShiroKit.getUser();
        if (null == user) {
            return;
        }

        //Get the parameters of the intercept method
        String className = point.getTarget().getClass().getName();
        Object[] params = point.getArgs();

        //Get the operation name
        BussinessLog annotation = currentMethod.getAnnotation(BussinessLog.class);
        String bussinessName = annotation.value();
        String key = annotation.key();
        String dictClass = annotation.dict();

        StringBuilder sb = new StringBuilder();
        for (Object param : params) {
            sb.append(param);
            sb.append(" & ");
        }

        // If there are changes involved, compare the changes
        String msg;
        if (bussinessName.indexOf("modify") ! = -1 || bussinessName.indexOf("edit") ! = -1) {
            Object obj1 = LogObjectHolder.me().get();
            Map<String, String> obj2 = HttpKit.getRequestParameters();
            msg = Contrast.contrastObj(dictClass, key, obj1, obj2);
        } else {
            Map<String, String> parameters = HttpKit.getRequestParameters();
            AbstractDictMap dictMap = DictMapFactory.createDictMap(dictClass);
            msg = Contrast.parseMutiKey(dictMap,key,parameters);
        }

        LogManager.me().executeLog(LogTaskFactory.bussinessLog(user.getId(), bussinessName, className, methodName, msg));
    }
}


/**
 * Add dictionaries
 @param dictValues Format e.g. "1:enable;2:disable;3:freeze"
 */
@BussinessLog(value = "Add dictionary record", key = "dictName,dictValues", dict = com.stylefeng.guns.common.constant.Dict.DictMap)
@RequestMapping(value = "/add")
@Permission(Const.ADMIN_NAME)
@ResponseBody
public Object add(String dictName, String dictValues) {
    if (ToolUtil.isOneEmpty(dictName, dictValues)) { if (ToolUtil.isOneEmpty(dictName, dictValues)) {
        throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
    }
    dictService.addDict(dictName, dictValues);
    return SUCCESS_TIP;
}


操作ログを記録する

<ブロッククオート

このステップは、最も重要な部分です

原則:カスタムアノテーション@BussinessLog(任意に命名可能)を使用し、ビジネス名、変更されるエンティティの一意の識別子、辞書(キーの中国名とフィールドの中国名を見つけるために使用)を定義し、AOPを介して、@BussinessLogアノテーションを追加したすべてのメソッドをインターセプトし、アノテーション内のプロパティを解析し、対応する操作ログテーブルにそれらを記録します。 操作ログを完了するために、処理ログテーブルに

BussinessLog

import com.stylefeng.guns.common.constant.tips.ErrorTip;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.exception.InvalidKaptchaException;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.log.factory.LogTaskFactory;
import com.stylefeng.guns.core.shiro.ShiroKit;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.UnknownSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation;
import org.springframework.web.bind.annotation;
import org.springframework.web.bind.annotation;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.UndeclaredThrowableException;

import static com.stylefeng.guns.core.support.HttpKit.getIp;
import static com.stylefeng.guns.core.support.HttpKit.getRequest;

getRequest; /**
 * global exception interceptor (intercept all controllers) (all methods with @RequestMapping annotation will be intercepted)
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * Intercept business exceptions
     */
    @ExceptionHandler(BussinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorTip notFount(BussinessException e) {
        LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e));
        getRequest().setAttribute("tip", e.getMessage());
        log.error("business exception:", e);
        return new ErrorTip(e.getCode(), e.getMessage());
    }

    /**
     * User is not logged in
     */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String unAuth(AuthenticationException e) {
        log.error("User not logged in: ", e);
        return "/login.html";
    }

    /**
     * Account is frozen
     */
    @ExceptionHandler(DisabledAccountException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String accountLocked(DisabledAccountException e, Model model) {
        String username = getRequest().getParameter("username");
        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "account frozen", getIp()));
        model.addAttribute("tips", "Account is frozen");
        return "/login.html";
    }

    /**
     * Account password error
     */
    @ExceptionHandler(CredentialsException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String credentials(CredentialsException e, Model model) {
        String username = getRequest().getParameter("username");
        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "Account password error", getIp()));
        model.addAttribute("tips", "Account password error");
        return "/login.html";
    }

    /**
     * Captcha error
     */
    @ExceptionHandler(InvalidKaptchaException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String credentials(InvalidKaptchaException e, Model model) {
        String username = getRequest().getParameter("username");
        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "CaptchaError", getIp()));
        model.addAttribute("tips", "CaptchaError");
        return "/login.html";
    }

    /**
     * No access to this resource
     */
    @ExceptionHandler(UndeclaredThrowableException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public ErrorTip credentials(UndeclaredThrowableException e) {
        getRequest().setAttribute("tip", "PermissionsException");
        log.error("Permission exception! ", e);
        return new ErrorTip(BizExceptionEnum.NO_PERMITION);
    }

    /**
     * Intercept unknown runtime exceptions
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorTip notFount(RuntimeException e) {
        LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e));
        getRequest().setAttribute("tip", "Server unknown runtime exception");
        log.error("Runtime exception:", e);
        return new ErrorTip(BizExceptionEnum.SERVER_ERROR);
    }

    /**
     * Exception interception interception for session failure
     */
    @ExceptionHandler(InvalidSessionException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String sessionTimeout(InvalidSessionException e, Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("tips", "sessionTimeout");
        assertAjax(request, response);
        return "/login.html";
    }

    /**
     * session exception
     */
    @ExceptionHandler(UnknownSessionException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String sessionTimeout(UnknownSessionException e, Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("tips", "sessionTimeout");
        assertAjax(request, response);
        return "/login.html";
    }

    private void assertAjax(HttpServletRequest request, HttpServletResponse response) {
        if (request.getHeader("x-requested-with") ! = null
                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            //If it's an ajax request the response header will have, x-requested-with
            response.setHeader("sessionstatus", "timeout");/

AOPを傍受する@BussinessLogアノテーション

import com.stylefeng.guns.common.annotion.log.BussinessLog;
import com.stylefeng.guns.common.constant.dictmap.base.AbstractDictMap;
import com.stylefeng.guns.common.constant.dictmap.factory.DictMapFactory;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.log.factory.LogTaskFactory;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.core.util.Contrast;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang;
import org.aspectj.lang.annotation;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect;
import java.util.Map;

/**
 * Logging
 */
@Aspect
@Component
public class LogAop {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut(value = "@annotation(com.stylefeng.guns.common.annotion.log.BussinessLog)")
    public void cutService() {
    }

    @Around("cutService()")
    public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {

        //Execute the business first
        Object result = point.proceed();

        try {
            handle(point);
        } catch (Exception e) {
            log.error("Logging error! ", e);
        }

        return result;
    }

    private void handle(ProceedingJoinPoint point) throws Exception {

        //Get the name of the intercepted method
        Signature sig = point.getSignature();
        MethodSignature msig = null;
        if (! (sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("This annotation can only be used for methods");
        }
        msig = (MethodSignature) sig;
        Object target = point.getTarget();
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        String methodName = currentMethod.getName();

        // If the current user is not logged in, no logging is done
        ShiroUser user = ShiroKit.getUser();
        if (null == user) {
            return;
        }

        //Get the parameters of the intercept method
        String className = point.getTarget().getClass().getName();
        Object[] params = point.getArgs();

        //Get the operation name
        BussinessLog annotation = currentMethod.getAnnotation(BussinessLog.class);
        String bussinessName = annotation.value();
        String key = annotation.key();
        String dictClass = annotation.dict();

        StringBuilder sb = new StringBuilder();
        for (Object param : params) {
            sb.append(param);
            sb.append(" & ");
        }

        // If there are changes involved, compare the changes
        String msg;
        if (bussinessName.indexOf("modify") ! = -1 || bussinessName.indexOf("edit") ! = -1) {
            Object obj1 = LogObjectHolder.me().get();
            Map<String, String> obj2 = HttpKit.getRequestParameters();
            msg = Contrast.contrastObj(dictClass, key, obj1, obj2);
        } else {
            Map<String, String> parameters = HttpKit.getRequestParameters();
            AbstractDictMap dictMap = DictMapFactory.createDictMap(dictClass);
            msg = Contrast.parseMutiKey(dictMap,key,parameters);
        }

        LogManager.me().executeLog(LogTaskFactory.bussinessLog(user.getId(), bussinessName, className, methodName, msg));
    }
}



BussinessLogの使用例

/**
 * Add dictionaries
 @param dictValues Format e.g. "1:enable;2:disable;3:freeze"
 */
@BussinessLog(value = "Add dictionary record", key = "dictName,dictValues", dict = com.stylefeng.guns.common.constant.Dict.DictMap)
@RequestMapping(value = "/add")
@Permission(Const.ADMIN_NAME)
@ResponseBody
public Object add(String dictName, String dictValues) {
    if (ToolUtil.isOneEmpty(dictName, dictValues)) { if (ToolUtil.isOneEmpty(dictName, dictValues)) {
        throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
    }
    dictService.addDict(dictName, dictValues);
    return SUCCESS_TIP;
}


3. 例外のログ取得

例外の記録は、実は繰り返し行われるもので、例外がスローされたことを記録することで、統一的に処理することも可能です

import com.stylefeng.guns.common.constant.tips.ErrorTip;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.exception.InvalidKaptchaException;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.log.factory.LogTaskFactory;
import com.stylefeng.guns.core.shiro.ShiroKit;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.UnknownSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation;
import org.springframework.web.bind.annotation;
import org.springframework.web.bind.annotation;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.UndeclaredThrowableException;

import static com.stylefeng.guns.core.support.HttpKit.getIp;
import static com.stylefeng.guns.core.support.HttpKit.getRequest;

getRequest; /**
 * global exception interceptor (intercept all controllers) (all methods with @RequestMapping annotation will be intercepted)
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * Intercept business exceptions
     */
    @ExceptionHandler(BussinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorTip notFount(BussinessException e) {
        LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e));
        getRequest().setAttribute("tip", e.getMessage());
        log.error("business exception:", e);
        return new ErrorTip(e.getCode(), e.getMessage());
    }

    /**
     * User is not logged in
     */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String unAuth(AuthenticationException e) {
        log.error("User not logged in: ", e);
        return "/login.html";
    }

    /**
     * Account is frozen
     */
    @ExceptionHandler(DisabledAccountException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String accountLocked(DisabledAccountException e, Model model) {
        String username = getRequest().getParameter("username");
        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "account frozen", getIp()));
        model.addAttribute("tips", "Account is frozen");
        return "/login.html";
    }

    /**
     * Account password error
     */
    @ExceptionHandler(CredentialsException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String credentials(CredentialsException e, Model model) {
        String username = getRequest().getParameter("username");
        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "Account password error", getIp()));
        model.addAttribute("tips", "Account password error");
        return "/login.html";
    }

    /**
     * Captcha error
     */
    @ExceptionHandler(InvalidKaptchaException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String credentials(InvalidKaptchaException e, Model model) {
        String username = getRequest().getParameter("username");
        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "CaptchaError", getIp()));
        model.addAttribute("tips", "CaptchaError");
        return "/login.html";
    }

    /**
     * No access to this resource
     */
    @ExceptionHandler(UndeclaredThrowableException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public ErrorTip credentials(UndeclaredThrowableException e) {
        getRequest().setAttribute("tip", "PermissionsException");
        log.error("Permission exception! ", e);
        return new ErrorTip(BizExceptionEnum.NO_PERMITION);
    }

    /**
     * Intercept unknown runtime exceptions
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorTip notFount(RuntimeException e) {
        LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e));
        getRequest().setAttribute("tip", "Server unknown runtime exception");
        log.error("Runtime exception:", e);
        return new ErrorTip(BizExceptionEnum.SERVER_ERROR);
    }

    /**
     * Exception interception interception for session failure
     */
    @ExceptionHandler(InvalidSessionException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String sessionTimeout(InvalidSessionException e, Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("tips", "sessionTimeout");
        assertAjax(request, response);
        return "/login.html";
    }

    /**
     * session exception
     */
    @ExceptionHandler(UnknownSessionException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String sessionTimeout(UnknownSessionException e, Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("tips", "sessionTimeout");
        assertAjax(request, response);
        return "/login.html";
    }

    private void assertAjax(HttpServletRequest request, HttpServletResponse response) {
        if (request.getHeader("x-requested-with") ! = null
                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            //If it's an ajax request the response header will have, x-requested-with
            response.setHeader("sessionstatus", "timeout");/

プロジェクトアドレス :https://gitee.com/Selegant/logs-demo.git