java 自定义注解储存日志到数据库

新建一个包,创建注释类
在这里插入图片描述

package com.jeeplus.modules.pc.config;

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

/**
 * @author Administrator
 */

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface HlwyyLogger {

// category 和value描述方法的实际作用

    String value() default "";
    int category() default 0;

}

现在来写HlwyyLogger 注解的实现类

import com.jeeplus.core.persistence.CustomException;

import com.jeeplus.modules.pc.doctormodel.entity.DtDoctorsofPc;
import com.jeeplus.modules.pc.doctormodel.service.DtDoctorsofPcService;
import com.jeeplus.modules.pc.logrecord.entity.DtLogRecordofPc;
import com.jeeplus.modules.pc.logrecord.service.DtLogRecordofPcService;
import com.jeeplus.modules.pc.tools.HttpContextUtils;
import com.jeeplus.modules.pc.tools.IpUtilsofDiy;
import com.jeeplus.modules.pc.tools.JSONUtils;
import com.jeeplus.modules.sys.security.util.JWTUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author Administrator
 */
@Aspect
@Component
public class HlwyyLoggerImpl {


           //本地异常日志记录对象 
        private final static Logger logger = LoggerFactory.getLogger(HlwyyLogger.class);
        
        @Autowired(required = false)
         private DtDoctorsofPcService dtDoctorsService;
         
      //注入Service用于把日志保存数据库 
        @Autowired(required = false)
        private DtLogRecordofPcService dtLogRecordofPcService;

    //Controller层切点
    @Pointcut("@annotation(com.jeeplus.modules.pc.config.HlwyyLogger)")
    public void HlwyyLogger() {
    }

    @Before("HlwyyLogger()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

    }

     //joinPoint 切点 

    @Around("HlwyyLogger()")
    public Object around(ProceedingJoinPoint point) throws CustomException {
        // 执行方法
        Object result = null;
        this.checkPermission(point);
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }

    void checkPermission(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        HlwyyLogger syslog = method.getAnnotation(HlwyyLogger.class);
        Boolean b = false;
        if (syslog != null) {
            try {
                String params = JSONUtils.beanToJson(syslog.value());
                String params1 = JSONUtils.beanToJson(syslog.category());
                logger.info("参数为:" + params);
                logger.info("参数为:" + params1);

                // 获取request(没有token可以不用写)
                HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
                DtLogRecordofPc dtLogRecordofPc=new DtLogRecordofPc();
                try{
                    String username= JWTUtil.getLoginName(request.getHeader("token"));
                    if(!StringUtils.isBlank(username))
                    {
                        DtDoctorsofPc doctor=this.dtDoctorsService.findUniqueByProperty("doctor_name",username);
                        if(doctor!=null)
                        {
                            dtLogRecordofPc.setDoctorId(Integer.parseInt(doctor.getId()));
                        }
                    }
                }catch (Exception e)
                {

                }
                //需要被存入数据库的字段
                dtLogRecordofPc.setCreateTime(new Date());
                dtLogRecordofPc.setStatus(1);
                dtLogRecordofPc.setContent(params+" url: "+request.getRequestURI());
                dtLogRecordofPc.setCategory(syslog.category());
                dtLogRecordofPc.setType(2);
                dtLogRecordofPc.setUserAgent(request.getHeader("user-agent"));
                dtLogRecordofPc.setIp(IpUtilsofDiy.getIpAddr(request));
                this.dtLogRecordofPcService.save(dtLogRecordofPc);
            } catch (Exception e) {
                logger.debug(e.getMessage());
            }
        }

    }
}

注解的实现类(也可以说是切点类)写完,我们就可以对自己的接口添加注解从而将你的操作步骤存入数据库

在这里插入图片描述
在这里插入图片描述

红色框住的就是我们需要添加的注解
由于我是两个端的日志写在一起所以需要 “category”这个字段来区分,1是后台端,2是用户端。不需要区分的同学只写上注解和你的接口说明(value)就可以啦
在这里插入图片描述

感谢观看!!!
下次再见!!!
我是一条小咸鱼

AOP(Aspect-Oriented Programming,面向切面编程)是一种用于将横切关注点从业务逻辑中分离出来的技术。通过自定义注解结合AOP可以很方便地实现诸如日志记录、权限检查等功能。 ### 使用 AOP 和自定义注解记录日志 #### 实现步骤: 1. **创建自定义注解** 定义一个注解,例如 `@LogAnnotation`,用来标记需要记录日志的方法。 ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface LogAnnotation { String description() default "默认描述"; } ``` 2. **配置 AOP 切面** 创建一个切面类,并在其中拦截被标注了该注解的方法,在方法执行前或执行后插入日志处理逻辑。 ```java @Aspect @Component public class LogAspect { private static final Logger logger = LoggerFactory.getLogger(LogAspect.class); // 拦截所有使用了 @LogAnnotation 注解的方法 @Around("@annotation(logAnnotation)") public Object logExecutionTime(ProceedingJoinPoint joinPoint, LogAnnotation logAnnotation) throws Throwable { long start = System.currentTimeMillis(); try { return joinPoint.proceed(); // 执行目标方法并返回结果 } finally { long executionTime = System.currentTimeMillis() - start; Signature signature = joinPoint.getSignature(); StringBuilder sb = new StringBuilder("Method "); sb.append(signature.toShortString()) .append(" executed in ") .append(executionTime) .append(" ms.") .append("\nDescription: ") .append(logAnnotation.description()); logger.info(sb.toString()); // 记录日志信息 } } } ``` 3. **应用注解到业务方法** 将自定义注解添加至希望监控其运行情况的服务层方法上即可触发相应的日志行为。 ```java @Service public class UserService { @LogAnnotation(description="查询用户基本信息") public void queryUserInfo(String userId){ // 具体操作... } } ``` 4. **测试验证功能是否正常工作** --- ### 注意事项 - 确保项目已经引入 Spring 的依赖并且支持 AOP 功能; - 自定义注解属性可以根据需求设计得更为丰富如指定级别等; - 日志输出位置也可以进一步优化为数据库存储或者其他形式保存下来便于后续分析;
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值