1、使用AspectJ写日志
2、代码实现
定义接口:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;
@Component
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogTestUtil
{
String logTest() default "string";
}
定义切面:
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class LogTestUtilWapper
{
private static final Logger LOGGER = xxx;
public LogTestUtilWapper()
{
LOGGER.info("------------LogTestUtilWapper init-------------");
}
@Pointcut(value = "execution(@LogTestUtil * com.huawei..*Main.*(*))")
private void pointCut()
{
}
@Before(value = "pointCut()")
public void beforeLog()
{
LOGGER.info("------------before-------------");
}
@Around("pointCut() && args(name)")
public Object aroundComplete(ProceedingJoinPoint jp, String name)
{
// 获取LogTestUtil注解参数
MethodSignature methodSignature = (MethodSignature) jp.getSignature();
Method method = methodSignature.getMethod();
String logStr = method.getAnnotation(LogTestUtil.class).logTest();
System.out.println(logStr + "------" + name);
// 调用业务代码
Object result = null;
try
{
LOGGER.info("------------before--------around--------");
result = jp.proceed();
LOGGER.info("------------after--------around--------");
}
catch (Throwable e)
{
LOGGER.info("------------fail----------around--------");
}
return result;
}
}
测试:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class TestMain
{
private static final Logger LOGGER = xxx;
@LogTestUtil
public void doSth(String name)
{
LOGGER.info("do sth!!!!!!!!!" + name);
}
public TestMain()
{
doSth("name");
}
public static void main(String args[])
{
String path = "spring/applicationContext.xml";
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext(path);
TestMain test = (TestMain)context.getBean("testMain");
test.doSth("test");
}
}
参考博客:
Spring AOP使用@AspectJ实现日志管理:
https://blog.csdn.net/u012554102/article/details/50443780
Spring AOP实现复杂的日志记录(自定义注解):
https://blog.csdn.net/mlc1218559742/article/details/51778224
AspectJ基本用法: