利用spring el做系统日志

来源:互联网 发布:mac炒股软件哪个好 编辑:程序博客网 时间:2024/06/05 19:27

最近用到了系统日记,不仅需要详细操作,还会调用第三方http应用,同时日记必须详细,

由于系统用到了spring,就用spring el表达式 和aop吧

1.首先注解

/**
 * @author zhangzhengyi
 * 日志描述,某一方法需要记录日志的,请添加该注解
 *
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LogDescription {

 /**
  * @return
  * 日记描述,spring el表达式
  */
 public String description() default "no description";

 /**
  * @return
  * 操作类型
  */
 public String type() default "no type";

 /**
  * @return
  * 实体表
  */
 public String entityType() default "no entityType";
}


2.service方法

@Service
public class TestLogService {
 @LogDescription(type="test", entityType="Config",  
    description="更新系统配置参数:#{#basicVariable.name} = #{#basicVariable.value}") 
 
 public void test(BasicVariable basicVariable) {
  System.out.println("test更新系统配置参数");
 }
}

BasicVariable是javabean


3.aop


/**
 * @author zhangzhengyi
 * 日志操作 aop
 * 如果日记数据量大,可用多线程模式
 */
public class LogAspect {
 //~ Static fields ==================================================================================================
 //缓存有@OperationDescription方法参数名称
 private static Map<String, String[]> parameterNameCaches = new ConcurrentHashMap<String, String[]>();
 //缓存SPEL Expression
 private static Map<String, Expression> spelExpressionCaches = new ConcurrentHashMap<String, Expression>();
 
 private static ExpressionParser parser = new SpelExpressionParser();
 private static LocalVariableTableParameterNameDiscoverer parameterNameDiscovere =
  new LocalVariableTableParameterNameDiscoverer();

 //~ Instance fields ================================================================================================
 private Logger logger = Logger.getLogger(LogAspect.class);
 
 /*@Autowired
 private OperLogService operLogService;*/

 //~ Methods ========================================================================================================
 /**
  * 对所有Service类,方法含有@OperationDescription,进行@Around拦截
  */
 
 public Object advice(ProceedingJoinPoint joinPoint, LogDescription annotation) throws Throwable {
     System.out.println("=====advice=======");
  Object result = joinPoint.proceed();
     saveLog(joinPoint, annotation);
        return result;
    }
 
 /**
  * 保存操作日志
  *
  * @param joinPoint
  * @param annotation
  */
 private void saveLog(ProceedingJoinPoint joinPoint, LogDescription annotation) {
  String descpTemp = annotation.description();
        String descption = executeTemplate(descpTemp, joinPoint);
        String entityType = annotation.entityType();
        String type = annotation.type();  
        System.out.println("descpTemp="+descpTemp+" descption="+descption);
        if (logger.isDebugEnabled()) {  
         String methodName = joinPoint.getSignature().getName();
          Log.debug(descption) ;
        }  
        
        //取到当前的操作用户  
      //User user=null;
        //if(user!=null){  
            try{   //记录日志,可以远程调用 ,或者入库
             /*OperLog operLog=new OperLog();  
                  
             operLog.setCreatetime(new Date());  
             operLog.setOperatorId(user.getOperatorId());  
             operLog.setOperatorName(user.getOperatorName());  
             operLog.setExeOperation(descption);  
             operLog.setExeType(type.getType());
             operLog.setEntityType(entityType);
                  
             operLogService.insertEntity(operLog);*/
            }catch(Exception ex){  
                logger.error(ex.getMessage());  
            }  
       // }
 }
 
 /**
  * 解析执行OperationDescription 的description模板。
  *
  * @param template
  * @param joinPoint
  * @return
  */
 private String executeTemplate(String template, ProceedingJoinPoint joinPoint) {
  // get method parameter name
  String methodLongName = joinPoint.getSignature().toLongString();
  String[] parameterNames =  parameterNameCaches.get(methodLongName);
  if(parameterNames == null) {
   Method method = getMethod(joinPoint);
   parameterNames = parameterNameDiscovere.getParameterNames(method);
   
   parameterNameCaches.put(methodLongName, parameterNames);
  }
  
  // add args to expression context
  StandardEvaluationContext context = new StandardEvaluationContext();
  Object[] args = joinPoint.getArgs();
  if(args.length == parameterNames.length) {
   for(int i=0, len=args.length; i<len; i++){
    
    context.setVariable(parameterNames[i], args[i]);
   }
  }
  
  //cacha expression
  Expression expression = spelExpressionCaches.get(template);
  if(expression == null) {
   expression = parser.parseExpression(template, new TemplateParserContext());
   spelExpressionCaches.put(template, expression);
  }
  
  String value = expression.getValue(context, String.class);
  
  return value;
 }
 
 /**
  * 获取当前执行的方法
  * @param joinPoint
  * @return
  */
 private Method getMethod(ProceedingJoinPoint joinPoint) {
  String methodLongName = joinPoint.getSignature().toLongString();
  
  Method[] methods = joinPoint.getTarget().getClass().getMethods();
  Method method = null;
  for(int i=0, len=methods.length; i<len; i++) {
   
   if(methodLongName.equals(methods[i].toString())) {
    method = methods[i];
    break;
   }
  }
  return method;
 }
}


4.在springContext.xml添加配置

<!-- 使用annotation定义事务 -->
 <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
 
  <!-- 日记aop配置 -->
 <aop:config proxy-target-class="true" />
 
 <bean id="logAspect" class="com.flaginfo.log.LogAspect">
  
 </bean>
 <aop:config>
  <aop:aspect id="log" ref="logAspect">
  <aop:pointcut id="aop" expression="execution (* com.flaginfo.service.*Service.*(..))  and @annotation(annotation)"/>
  <aop:around pointcut-ref="aop" method="advice"   />
 </aop:aspect>
 </aop:config>
 
 5.最后测试

public class TestService {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
    //挂断
  
  //ApplicationContext ac = new AnnotationConfigApplicationContext("applicationContext.xml");
  
  ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
  TestLogService testLogService = ac.getBean("testLogService",TestLogService.class);
  BasicVariable basicVariable = new BasicVariable();
  
  basicVariable.setName("zs");
  basicVariable.setValue("22");
   testLogService.test(basicVariable);
 }

}

结果:



ok,日志配置成功



0 0
原创粉丝点击