通过注解实现记录日志的功能

记得以前看spring in action上面介绍AOP的那章,提到了可以用切面来记录系统的日志,实现日志和业务逻辑之间的解耦。

前些日子公司的系统也有了记录日志的需求,遂写了一个通过注解、AOP来实现记录系统日志的功能,以下是实现代码,分享出来大家一起学习,看看有无改进的地方


AOP配置

 <span style="white-space:pre">	</span><bean id="logAspect" class="com.util.LogAspect"/>     
         <aop:config>   
            <aop:aspect ref="logAspect">   
                <aop:pointcut id="logPointCut" expression="execution(* com.service.*.add*(..))||
                execution(* com.service.*.update*(..))"/>   
                <aop:after pointcut-ref="logPointCut" method="doSystemLog"/>   
            </aop:aspect>   
        </aop:config>   

日志处理类


/**
 * 通过Spring AOP来添加系统日志
 */ 
public class LogAspect extends BaseAction{ 
 
    private static final long serialVersionUID = -5063868902693772455L; 
 
    private static String splitParaStr = ",";
    private static String splitNameValueStr = ":";

    @Autowired
	LogServiceImpl logService;
    
    @SuppressWarnings( { "rawtypes", "unchecked" } ) 
    public void doSystemLog(JoinPoint point) throws Throwable {   
        Object[] param = point.getArgs(); 
        Class[] parameterTypes = ((MethodSignature)point.getSignature()).getMethod().getParameterTypes();

        Method method = null; 
        String methodName = point.getSignature().getName(); 
        
        if (!("set".startsWith(methodName)&&!"get".startsWith(methodName)&&!"query".startsWith(methodName)&&!"sel".startsWith(methodName))){ //不需要记录日志的方法名
            Class targetClass = point.getTarget().getClass();   
            method = targetClass.getMethod(methodName,parameterTypes); 
            if (method != null) { 
                boolean hasAnnotation = method.isAnnotationPresent(com.util.Log.class); 
                if (hasAnnotation) { //判断是否为log的注解
                	com.harmony.lottery.util.Log annotation = method.getAnnotation(com.harmony.lottery.util.Log.class);   
                  //验证是否登录
                	ActionContext actionContext = ActionContext.getContext();
                	if(actionContext == null){
                		return;
                	}
                    Map session = actionContext.getSession();
        			SysUser sysUser=(SysUser) session.get("user");
					if (sysUser != null) {
						com.domain.Log logInfo = new com.domain.Log();
						logInfo.setAddPerson(sysUser.getUserId());
						logInfo.setAddTime(new Date());
						logInfo.setRemark(sysUser.getUserId() + getParamsRemark(annotation,param));//获得注解参数值
						logService.insert(logInfo);
					}   
                }   
            }   
        }   
    } 
     
    /**
     * 通过java反射来从传入的参数object里取出我们需要记录的id,name等属性,
     * 此处我取出的是id
     */ 
    private String getID(Object obj,String param){ 
        if(obj instanceof String){ 
            return obj.toString(); 
        } 
        PropertyDescriptor pd = null; 
        Method method = null; 
        String v = ""; 
        try{ 
            pd = new PropertyDescriptor(param, obj.getClass()); 
            method = pd.getReadMethod();   
            v = String.valueOf(method.invoke(obj));  
        }catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return v; 
    } 
    private String getParamsRemark(com.harmony.lottery.util.Log annotation, Object[] param){
    	String propertys = annotation.propertys();
    	StringBuffer sb = new StringBuffer();
    	if(null != propertys&&!"".equals(propertys)){
    		String[] propertysRemark = annotation.propertys().split(splitParaStr);
        	for (String property : propertysRemark) {//按参数对象属性,取参数值
    			String name = property.split(splitNameValueStr)[0];
    			String value = property.split(splitNameValueStr)[1];
    			sb.append(name + splitNameValueStr + getID(param[0],value) +splitParaStr);
    		}
        	return  annotation.operation()+sb.toString().substring(0,sb.length()-1);
    	}else{
    		String oper = annotation.operation();
    		List<String> list = PatternUtil.getList("\\{(\\d*)\\}",oper);//按参数位置取参数值
    		for (int i=0;i<list.size();i++) {
    			String str = list.get(i);
    			Object obj = param[Integer.parseInt(str)];
    			oper = PatternUtil.replease("\\{"+Integer.parseInt(str)+"\\}", oper, obj.toString());
			}
    		return oper;
    	}
    }
}  

注解接口的定义

import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.*;
/**
 * 类的方法描述注解
 * @author LuoYu
 */ 
@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 
@Documented 
@Inherited 
public @interface Log { 
 
    public String operation() default ""; 
    
    public String propertys() default ""; 
} 

具体实现类的配置,其中一个为对象属性的配置方式,一种为参数顺序的配置方式,格式可以根据自己的需要更改


@Log(operation="修改参数-->",propertys="参数名称:name,修改后的值为:value")
	public void update(SysParam record) {
		sysParamMapper.updateByPrimaryKeySelective(record);
}

@Log(operation="为代销商{1}充值{2}元")
<span style="white-space:pre">	</span>public void recharge(String userId,String agencyId,BigDecimal money,int type,Date date,String remark)

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AOP是一个强大的框架,可以帮助我们实现各种切面,其中包括日志记录。下面是实现日志记录的步骤: 1. 添加Spring AOP依赖 在Maven或Gradle中添加Spring AOP依赖。 2. 创建日志切面 创建一个用于记录日志的切面。这个切面可以拦截所有需要记录日志的方法。在这个切面中,我们需要使用@Aspect注解来声明这是一个切面,并使用@Pointcut注解来定义哪些方法需要被拦截。 ```java @Aspect @Component public class LoggingAspect { @Pointcut("execution(* com.example.demo.service.*.*(..))") public void serviceMethods() {} @Around("serviceMethods()") public Object logServiceMethods(ProceedingJoinPoint joinPoint) throws Throwable { // 获取方法名,参数列表等信息 String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); // 记录日志 System.out.println("Method " + methodName + " is called with args " + Arrays.toString(args)); // 执行方法 Object result = joinPoint.proceed(); // 记录返回值 System.out.println("Method " + methodName + " returns " + result); return result; } } ``` 在上面的代码中,我们使用了@Around注解来定义一个环绕通知,它会在拦截的方法执行前后执行。在方法执行前,我们记录了该方法的名称和参数列表,然后在方法执行后记录了该方法的返回值。 3. 配置AOP 在Spring的配置文件中配置AOP。首先,我们需要启用AOP: ```xml <aop:aspectj-autoproxy/> ``` 然后,我们需要将创建的日志切面添加到AOP中: ```xml <bean id="loggingAspect" class="com.example.demo.aspect.LoggingAspect"/> <aop:config> <aop:aspect ref="loggingAspect"> <aop:pointcut id="serviceMethods" expression="execution(* com.example.demo.service.*.*(..))"/> <aop:around method="logServiceMethods" pointcut-ref="serviceMethods"/> </aop:aspect> </aop:config> ``` 在上面的代码中,我们将创建的日志切面声明为一个bean,并将其添加到AOP中。我们还定义了一个切入点,并将其与日志切面的方法进行关联。 4. 测试 现在,我们可以测试我们的日志记录功能了。在我们的业务逻辑中,所有匹配切入点的方法都会被拦截,并记录它们的输入和输出。我们可以在控制台中看到这些日志信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值