首页 > 其他分享 >Use AOP to record system logs

Use AOP to record system logs

时间:2024-05-17 11:10:53浏览次数:17  
标签:Use java logs joinPoint record org import annotation description

Using AOP to Record System Logs:

1.Custom Annotation Class

Define a custom annotation class:

package com.java.common.annotion;
import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.PARAMETER}) // This annotation applies to methods and parameters
@Retention(RetentionPolicy.RUNTIME) // Runtime annotation
public @interface SystemControllerLog {
    String description() default "Default Controller Interface";
}

2. Define an Aspect Class

In the aspect class, define pointcuts for classes or methods with the custom annotation from step one:

package com.java.common.aspect;

import com.java.common.annotion.SystemControllerLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Aspect class to record common logs
 */
@Component
@Aspect
public class LogAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    // Pointcut for Controllers
    @Pointcut("@annotation(com.java.common.annotion.SystemControllerLog)")
    public void controllerAspect() {
    }

    // Pointcut for Services
    @Pointcut("@annotation(com.java.common.annotion.SystemServiceLog)")
    public void serviceAspect() {
    }

    /**
     * Before advice to log user actions in Controller layer
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            logger.info("============== Before Advice Start ==============");
            logger.info("Request Method: " + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()));
            logger.info("Method Description: " + getControllerMethodDescription(joinPoint));
        } catch (Exception exception) {
            logger.error("== Before Advice Exception ==");
            logger.error("Exception Message: {}", exception.getMessage());
        }
    }

    /**
     * Get method description from annotation in Controller layer
     */
    private String getControllerMethodDescription(JoinPoint joinPoint) throws ClassNotFoundException {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
}

3. Implement the Logging Logic in the Aspect Class

4. Add Annotations to the Classes or Methods that Require Logging

@GetMapping("/user")
@SystemControllerLog(description = "Test API Log")
@ResponseBody
public User user() {
    User user = new User();
    user.setName("theonefx");
    user.setAge(6666);
    return user;
}

Assume that the logging code and the business code are in different packages. You need to scan the corresponding aspect class; otherwise, it will not achieve the logging effect.

标签:Use,java,logs,joinPoint,record,org,import,annotation,description
From: https://www.cnblogs.com/zhangcheng1234/p/18197471

相关文章

  • php 判断 if (empty($user->published_at) != empty($user_input['published_at']))
    这里的逻辑是:如果$user->published_at为空,并且$user_input['published_at']不为空,或者如果$user->published_at不为空,并且$user_input['published_at']为空,那么条件将成立。这种检查通常用于确定某个值是否发生了变化,特别是从无到有或从有到无的情况。假设您的意图......
  • 面向 Reuse 的软件构造技术
    前几章介绍了软件构造的核心理论——ADT,核心技术——OOP,其核心是保证代码质量、提高代码安全性本章面向一个重要的外部指标:可复用性——如何构造出可在不同应用中重复使用的软件模块/API为什么复用?软件复用有两个视角:面向复用编程:开发出可复用的软件基于复用编程:利用已有的......
  • pyppeteer Execution context was destroyed, most likely because of a navigation
    一般情况下是当前page有开启新的页面,或者重定向之类的操作,然后重定向还没有完成的时候,就对page进行了操作,比如waitXpath之类的,就会导致该异常的出现。这个时候需要使用到函数page.waitForNavigation(timeout=timeout)但是怎么说呢,这个函数的使用,必须紧挨重定向开始以后,如......
  • Clickhouse常用整理& linux操作clickhouse命令
    进入click(不加上-m的话,进入之后只能一次写一行,不能建表)clickhouseclient-m 查看数据库showdatabases;创建一个数据库createdatabasedb_doit; 删除数据库dropdatabasedb_doit;查看表showtables;查看当前使用的数据库selectcurrentDatabas......
  • docker搭建Elasticsearch、Kibana、Logstash 同步mysql数据到ES
    一、前言在数据量大的企业级实践中,Elasticsearch显得非常常见,特别是数据表超过千万级后,无论怎么优化,还是有点力不从心!使用中,最首先的问题就是怎么把千万级数据同步到Elasticsearch中,在一些开源框架中知道了,有专门进行同步的!那就是Logstash。在思考,同步完怎么查看呢,这时Kibana映入......
  • pwn知识——House of Botcake
    个人理解感觉HouseofBotcake就是doublefree+overlapping+_IO_FILEattack的结合使用,需要对堆结构有着较为详细的理解,也要有能管理堆顺序的能力,建议写题的时候还是标一标堆的index,这样在利用堆的时候会比较方便些HouseofBotcake想要利用这个攻击,我们得先了解_IO_FILE的......
  • ClickHouse vs StarRocks 全场景MPP数据库选型对比
    ClickHousevsStarRocks选型对比面向列存的DBMS新的选择Hadoop从诞生已经十三年了,Hadoop的供应商争先恐后的为Hadoop贡献各种开源插件,发明各种的解决方案技术栈,一方面确实帮助很多用户解决了问题,但另一方面因为繁杂的技术栈与高昂的维护成本,Hadoop也渐渐地失去了原本......
  • CF965D Single-use Stones
    题目链接:因为青蛙最多跳\(l\)的距离,我们设\(l\)为一个区间,那么每个区间青蛙最多能跳过的只数,就是这个区间内石头的个数。(只要有一个区间青蛙没跳过去,那么整段就过不去了)因此青蛙能跳过去的最多只数就是所有区间长度为\(l\)的石头块数的最小值(确保无论踩在哪都能过河)#inclu......
  • the request was rejected because no multipart boundary was found
    报错:Failedtoparsemultipartservletrequest;nestedexceptionisjava.io.IOException:org.apache.tomcat.util.http.fileupload.FileUploadException:therequestwasrejectedbecausenomultipartboundarywasfound本地一个模块,在多种环境下测试过都OK,但是在一个......
  • pinus老项目启动遇'Property connector does not exist on type UserRpc'报错
    跟示例项目对比过,配置代码并无出入,尝试在示例中新增远程调用connectorRemote可用,证明代码配置正确尝试在示例项目中使用工作项目的配置文件包括引用的模块文件目录列表如下 packagespluginspackage.jsonpackage-lock.jsontsconfig.jsonyarn.lock 示例安装模块后,运......