提交 42ea222b 编写于 作者: 武汉红喜's avatar 武汉红喜

MonitorAspect demo

上级 5b880b59
......@@ -25,16 +25,7 @@
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
......@@ -46,18 +37,6 @@
<artifactId>aspectjtools</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
......@@ -66,6 +45,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
......
......@@ -11,12 +11,10 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface Monitor {
String DEFAULT_TAG_NAME = "@@USE_METHOD_NAME";
String tag() default "@@USE_METHOD_NAME";
String message() default "";
boolean heart() default false;
/**
* 标识每一个方法,全局唯一
*/
String tag();
}
......@@ -3,42 +3,41 @@ package org.hongxi.whatsmars.spring.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* Created by shenhongxi on 2016/8/10.
*/
@Component
@Aspect
public class MonitorAspect {
private String tagPrefix;
private static Logger logger = LoggerFactory.getLogger(MonitorAspect.class);
@Around(
value = "execution(* *(..)) && @annotation(monitor)",
argNames = "pjp,monitor"
)
public Object doUmpLogging(ProceedingJoinPoint pjp, Monitor monitor) throws Throwable {
// String tag = monitor.tag();
// boolean heart = monitor.heart();
String tag = monitor.tag();
long start = System.currentTimeMillis();
// record invocation (times)
logger.info("{} start time: {}", tag, start);
Object obj = null;
try {
obj = pjp.proceed();
} catch (Exception e) {
// record error
logger.error("{} invoke error", tag, e);
throw e;
} finally {
long end = System.currentTimeMillis();
// record time -> end - start
logger.info("{} cost time: {}", tag, end - start);
}
return obj;
}
public String getTagPrefix() {
return tagPrefix;
}
public void setTagPrefix(String tagPrefix) {
this.tagPrefix = tagPrefix;
}
}
package org.hongxi.whatsmars.spring.aspect;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLog {
String description() default "";
int logType();
}
package org.hongxi.whatsmars.spring.aspect;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
@Aspect
@Component
public class SystemLogAspect {
private static Logger logger = Logger.getLogger(SystemLog.class);
// Controller层切点
@Pointcut("@annotation(org.hongxi.whatsmars.spring.aspect.SystemLog)")
public void controllerAspect() {
}
// 操作记录
@After("controllerAspect()")
public void doAfter(JoinPoint joinPoint) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 读取session中的用户
// User user = SessionUtils.getUserFromSession(request);
// if(null == user){
// logger.info("未登录日志不记录");
// return;
// }
try {
Object[] args = getLogMethodDescription(joinPoint);
// *========数据库日志=========*//
// logService.saveLog(user.getId(), user.getAccount(), Integer.valueOf(args[1].toString()),
// IpUtils.getIpAddr(request), args[0].toString(),
// user.getManufacturerId(), reqDescription(request));
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
}
}
// 异常记录
@AfterThrowing(pointcut = "controllerAspect()", throwing = "exception")
public void doException(JoinPoint joinPoint, Exception exception) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 读取session中的用户
// User user = SessionUtils.getUserFromSession(request);
// if(null == user){
// logger.info("未登录日志不记录");
// return;
// }
try {
Object[] args = getLogMethodDescription(joinPoint);
// *========数据库日志=========*//
// logService.saveLog(user.getId(), user.getAccount(), LogType.EXCEPTION_LOG,
// IpUtils.getIpAddr(request), args[0].toString() + "-->" + exception.getMessage(),
// user.getManufacturerId(), reqDescription(request));
} catch (Exception e) {
// 记录本地异常日志
logger.error(e);
e.printStackTrace();
}
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解 切点
*/
@SuppressWarnings("rawtypes")
public static Object[] getLogMethodDescription(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class<?> targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
Object[] result = new Object[2];
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
result[0] = method.getAnnotation(SystemLog.class).description();
result[1] = method.getAnnotation(SystemLog.class).logType();
break;
}
}
}
return result;
}
}
package org.hongxi.whatsmars.spring.aspect.demo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* Created by shenhongxi on 2018/12/16.
*/
@ComponentScan(basePackages = "org.hongxi.whatsmars.spring.aspect")
@EnableAspectJAutoProxy
@Configuration
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Application.class);
ctx.refresh();
DemoService demoService = ctx.getBean(DemoService.class);
demoService.t();
}
}
package org.hongxi.whatsmars.spring.aspect.demo;
import org.hongxi.whatsmars.spring.aspect.Monitor;
import org.springframework.stereotype.Service;
/**
* Created by shenhongxi on 2018/12/15.
*/
@Service
public class DemoService {
@Monitor(tag = "spring.aspect.demo.DemoService.t")
public void t() {
for (int i = 0; i < 10000; i++) {
if (i < 9999) System.out.print(i + ",");
else System.out.println(i);
}
}
}
......@@ -15,8 +15,8 @@
<property name="cnName" value="火星" />
</bean>
<!-- MQ发消息线程池 -->
<bean id="taskMqExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >
<!-- 线程池 -->
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >
<!-- 核心线程数 -->
<property name="corePoolSize" value="10" />
<!-- 最大线程数 -->
......
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<resetJUL>true</resetJUL> </contextListener> -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %5p %40.40c:%4L - %m%n</pattern>
</encoder>
</appender>
<logger name="org.springframework.data.mongodb" level="debug" />
<root level="info">
<appender-ref ref="console" />
</root>
</configuration>
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册