日志管理---spring的aop进行管理

在java开发中日志的管理有很多种。我一般会使用过滤器,或者是Spring的拦截器进行日志的处理。如果是用过滤器比较简单,只要对所有的.do提交进行拦截,然后获取action的提交路径就可以获取对每个方法的调用。然后进行日志记录。使用过滤器的好处是可以自己选择性的对某一些方法进行过滤,记录日志。但是实现起来有点麻烦。

另外一种就是使用Spring的AOP了。这种方式实现起来非常简单,只要配置一下配置文件就可以了。可是这种方式会拦截下所有的对action的每个操作。使得效率比较低。不过想做详细日志这个方法还是非常好的。下面我就介绍一下使用Spring AOP进行日志记录的方式。

第一种。Spring AOP对普通类的拦截操作

首先我们要写一个普通类,此类作为日志记录类。 比如

package chen.hui.log

public classs MyLog{

//在类里面写方法,方法名诗可以任意的。此处我用标准的before和after来表示

public void before(){

System.out.println("被拦截方法调用之前调用此方法,输出此语句");

}

public void after(){

System.out.println("被拦截方法调用之后调用此方法,输出此语句");

}

}

其次我们在写一个类作为被拦截类(Spring的AOP就是拦截这个类里面的方法)

package chen.hui.log

public class Test{//此类中方法可以写任意多个。我只写一个

public void test(){

Sytem.out.println("测试类的test方法被调用");

}

}

最后进行配置文件的编写。在Spring的配置文件中我们需要进行几句话的配置

<bean id="testLog" class="chen.hui.log.MyLog"></bean> <!--将日志类注入到bean中。-->

<aop:config>
<aop:aspect id="b" ref="testLog"><!--调用日志类-->
<aop:pointcut id="log" expression="execution(* chen.hui.log.*.*(..))"/><!--配置在log包下所有的类在调用之前都会被拦截-->
<aop:before pointcut-ref="log" method="before"/><!--在log包下面所有的类的所有方法被调用之前都调用MyLog中的before方法-->
<aop:after pointcut-ref="log" method="after"/>><!--在log包下面所有的类的所有方法被调用之前都调用MyLog中的after方法-->

</aop:aspect>

</aop:config>



到此处整个程序完成,在MyLog类里面的before和after方法添加日志逻辑代码就可以完成日志的管理。以上是对普通类的管理,如果只想拦截某一个类。只要把倒数第二个 * 改成类名就可以了。



第二:使用Spring AOP对action做日志管理

如果是想拦截action对action做日志管理,基本和上面差不多,但是要注意。以下几点

首先还是要写一个普通类,不过此类中的方法需要传入参数。 比如

package chen.hui.log

import org.aspectj.lang.JoinPoint;

public classs MyLog{

//在类里面写方法,方法名诗可以任意的。此处我用标准的before和after来表示

//此处的JoinPoint类可以获取,action所有的相关配置信息和request等内置对象。

public void before(JoinPoint joinpoint){

joinpoint.getArgs();//此方法返回的是一个数组,数组中包括request以及ActionCofig等类对象

System.out.println("被拦截方法调用之前调用此方法,输出此语句");

}

public void after(JoinPoint joinpoint){

System.out.println("被拦截方法调用之后调用此方法,输出此语句");

}

}

其次我们在写一个action类作为被拦截类(Spring的AOP就是拦截这个类里面的方法)

package chen.hui.log

public class LoginAction{//此类中方法可以写任意多个。我只写一个

public void test(){

Sytem.out.println("测试类的test方法被调用");

}

}

最后进行配置文件的编写。在Spring的配置文件中我们需要进行几句话的配置

<bean id="testLog" class="chen.hui.log.MyLog"></bean> <!--将日志类注入到bean中。-->

<aop:config>
<aop:aspect id="b" ref="testLog"><!--调用日志类-->
<aop:pointcut id="log" expression="execution(* chen.hui.log.*.*(..))"/><!--配置在log包下所有的类在调用之前都会被拦截-->
<aop:before pointcut-ref="log" method="before"/><!--在log包下面所有的类的所有方法被调用之前都调用MyLog中的before方法-->
<aop:after pointcut-ref="log" method="after"/>><!--在log包下面所有的类的所有方法被调用之前都调用MyLog中的after方法-->

</aop:aspect>

</aop:config>



除了参数外其他地方基本和普通类相似。

需要注意的是:普通类可以监控单一的类,而action在配置文件中只能到包名而不能到action的类名。不然会报错。就是说如果要记录日志就要记录所有的action而不能记录其中一个,这是我试了好久得出的结果。如果有高手知道怎么记录单一的action或者有朋友有任何问题可以留下联系方式,大家相互交流,共同进步。

======================================================================
<bean id="logAspect" class="com.gosophia.logContent.LogAspectService.LogAspect" />
<aop:config proxy-target-class="true">
<aop:aspect ref="logAspect">
<aop:pointcut id="logPointCut"
expression="execution(* com.gosophia.commons.web.action.BaseSupportAction.*(..))" />
<aop:after-returning pointcut-ref="logPointCut"
method="doSystemLog" />
</aop:aspect>
</aop:config>

在action中这样用的
public class LogAspect {

@Autowired
private LogManagementWebService logManagementService;

private Log logger = LogFactory.getLog(LogAspect.class);

@SuppressWarnings("unchecked")
public void doSystemLog(JoinPoint point) throws Throwable {
String methodName = point.getSignature().getName();
//目标方法不为空
if(StringUtils.isNotEmpty(methodName)) {
//set与get方法除外
if(methodName.startsWith("_exe")) {

Class targetClass = point.getTarget().getClass();
Method method = targetClass.getMethod(methodName);

if(method!=null){
boolean hasAnnotation = method.isAnnotationPresent(LogRecord.class);
if(hasAnnotation) {
LogRecord annotation = method.getAnnotation(LogRecord.class);
String methodDescp = annotation.eventAction();
String targetc = annotation.eventTarget();
String DtoTarget;
Field h = null;
Class<? extends Object> myClass = point.getTarget().getClass();

//连同父类中的方法一起查找
while (!myClass.equals(BaseSupportAction.class)
&& !myClass.equals(Object.class)){
try{
h = myClass.getDeclaredField(targetc);
}catch (NoSuchFieldException e) {
// TODO: handle exception
}catch (SecurityException e) {
// TODO: handle exception
}

if (h != null){
break;
}

myClass = point.getTarget().getClass().getSuperclass();
}

Boolean bAccessible = h.isAccessible();
h.setAccessible(true);

if(h.get(point.getTarget()).toString().length()>2000){
DtoTarget = h.get(point.getTarget()).toString().substring(0, 2000);
} else {
DtoTarget = h.get(point.getTarget()).toString();
}

h.setAccessible(bAccessible);

//取到当前的操作用户
UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder
.getContext().getAuthentication().getPrincipal();

if(userDetails!=null) {
try {
LogContentDTO logContent = new LogContentDTO();
// 用户IP地址
HttpServletRequest request = ServletActionContext.getRequest();

// 当用户使用了代理服务器时
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
//用户IP
logContent.setEventResource(ip);
// 当前时间
Date now = new Date(System.currentTimeMillis());
DateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置显示格式
String dateString = date.format(now);
// 操作时间
logContent.setEventTime(dateString);
// 操作当前账户
logContent.setEventUserAccountName(userDetails.getUsername());
// 用户操作行为
logContent.setEventAction(methodDescp);
// 用户信息
logContent.setLogMessage(DtoTarget);
// 添加日志
logManagementService.addLogContent(logContent);
} catch(Exception ex) {
logger.error(ex.getMessage());
}
}

}
}
}
}

}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值