使用AOP实现监控日志并保存

最近项目中要做个效能监控的功能,经过考虑,觉得选择spring的AOP来实现。必须放在Web端。

例子如下:

import java.util.Date;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;

import com.csair.amp.web.webinf.common.model.LoginInfo;
import com.csair.smms.effmonitor.dto.MonitorLog;
import com.csair.smms.effmonitor.service.MonitorService;
import com.opensymphony.xwork2.ActionContext;

/**
* 效能监控日志类
*
* @author ahomeeye
*
* 2012-7-11 下午2:32:34
*/
@Aspect
public class EfficiencyMonitor {

@Autowired
private MonitorService monitorService;//保存日志信息的业务实现

// 登录日志,代表监控com.csair.amp.web.webinf.common.LoginAction类的login方法,可用通配符*
@After("execution(* com.csair.amp.web.webinf.common.LoginAction.login())")
public void loginLog() {
//从session中获取用户信息
LoginInfo u = (LoginInfo) ActionContext.getContext().getSession()
.get("user");
MonitorLog m = new MonitorLog();
m.setUsername(u.getUsername());
m.setLogtime(new Date());
m.setFunction(MonitorConstants.LOGIN);
m.setClassName("com.csair.amp.web.webinf.common.LoginAction");
m.setMethodName("login");
monitorService.insertMonitorLog(m);//保存日志信息

System.out.println("-------用户登录--username=" + u.getUsername());
}
}


需要导入两个AspectJ库:aspectjweaver.jar和aspectj.jar。

JavaBean类

public class MonitorLog implements Serializable {
private static final long serialVersionUID = 7707875472196483005L;
private int id;// 编号
private String username;// 用户名
private Date logtime;// 使用时间
private String function;// 使用功能
private String className;// 类名
private String methodName;// 方法名
//省略setter和getter方法
}


在applicationContext.xml文件里加入如下代码:

<!-- 指定自动搜索Bean组件、自动搜索切面类,前一个代表搜索Bean的包,后一个代表搜索切面类的包-->
<context:component-scan base-package="com.csair.amp.web.webinf,com.csair.amp.web.webinf.effmonitor">
<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>
<!-- 启动@AspectJ支持 -->
<!--<aop:aspectj-autoproxy/> 此标记与下面一行等效-->
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>


如果项目中使用了spring的自动装配(@Autowired)功能,还行在struts.xml文件中加入下面一行,意思是始终使用自动装配功能:
<constant name="struts.objectFactory.spring.autoWire.alwaysRespect" value="true" />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值