一、自定义注解
自定义切面注解@PrintlnLog 用来输出日志,注解权限 @Target({ElementType.METHOD}) 限制只在方法上使用,注解中只有一个参数 description ,用来自定义方法输出日志的描述。
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.METHOD})
@Documented
public @interface PrintlnLog {
/**
* 自定义日志描述信息文案
*
* @return
*/
String description() default "";
}
二、切面类
接下来编写@PrintlnLog 注解对应的切面实现,doBefore()中输出方法的自定义描述、入参、请求方式、请求url、被调用方法的位置等信息,doAround() 中打印方法返回结果。
注意: 如何想指定切面在哪个环境执行,可以用@Profile 注解,只打印某个环境的日志。
@Slf4j
@Aspect
@Component
//@Profile({"dev"}) //只对某个环境打印日志
public class LogAspect {
private static final String LINE_SEPARATOR = System.lineSeparator();
/**
* 以自定义 @PrintlnLog 注解作为切面入口
*/
@Pointcut("@annotation(com.chengxy.unifiedlog.config.PrintlnLog)")
public void PrintlnLog() {
}
/**
* @param joinPoint
* @author fu
* @description 切面方法入参日志打印
* @date 2020/7/15 10:30
*/
@Before("PrintlnLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String methodDetailDescription = this.getAspectMethodLogDescJP(joinPoint)