当前位置: 首页 > 知识库问答 >
问题:

带有REST日志的Spring JPA数据

秦鹏飞
2023-03-14

我使用本教程使用REST访问JPA数据,创建了一个简单的RESTful Web服务,用于访问数据库中的一些数据。它工作得很好。我喜欢它有多简单,我或多或少了解它的工作原理。

但是,有人要求我添加一些自定义日志记录。每当Web服务被调用日志时,都会生成“Start-time”,并在服务返回之前生成另一个日志“End-time”。有没有办法在不破坏我的包含@Query anotation的方法的情况下做到这一点

public interface PersonRepository extends PagingAndSortingRepository<Person, Long>

我有点希望会有一些注释,但我似乎什么也找不到。

有什么建议吗?

共有1个答案

白越
2023-03-14

听起来像是Spring AOP的案例!

从一个非常有用的教程(也是一个有用的SO答案)开始,我在我的TokenRepository中执行任何方法之前和之后创建了一些记录

@Repository
public interface TokenRepository extends CrudRepository<Token, String> {
}

有趣的是

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
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;

@Aspect
@Component
public class LoggingHandler {

    Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut("this(org.springframework.data.repository.Repository)")
    public void repository() { }

    @Pointcut("execution(* *.*(..))")
    protected void allMethod() { }

    //before -> Any resource annotated with @Repository annotation
    //and all method and function
    @Before("repository() && allMethod()")
    public void logBefore(JoinPoint joinPoint) {
        log.info("Entering in Method :  " + 
joinPoint.getSignature().getName() + " at " + System.currentTimeMillis());
    }

    //After -> All method within resource annotated with @Repository annotation
    @AfterReturning(pointcut = "repository() && allMethod()")
    public void logAfter(JoinPoint joinPoint) {
        log.info("Method Returned at : " + System.currentTimeMillis());
    }
}
 类似资料:
  • 我是不是漏掉了什么?

  • 问题内容: 如何记录我的Python错误? 问题答案: 在处理程序/块中使用,可将当前异常与跟踪信息一起记录在日志中,并附带一条消息。 现在查看日志文件:

  • 我仍然是java和spring的初学者,我已经在mysql中存储了一个名为< code>Offers的表,我试图逐行获取数据< code >其中Status == 0,我的表看起来像这样: 当我尝试运行我的代码时,它的返回 org.springframework.beans.factory。BeanCreationException:创建在类路径资源[org/springframework/boo

  • 问题内容: 这是我的日志输出 我想要每个日志消息的时间戳,即 这是我的log4j配置文件 我该怎么做? 问题答案: 在您的PatternLayout中使用。 也可以采用格式模式,就像您可以选择所需的元素一样。如果省略格式模式,则日期将为ISO8601格式。

  • 我是REST API和JSON的新手,我有一个初学者的问题。我试图使用的API根据以下模式请求参数: 请求参数示例如下: 但是,当我试图使用SoapUI和Postman测试这个API时,我只看到参数的键值对,我不知道如何在病人对象中嵌套ID和类型: SoapUI参数 邮递员参数

  • 问题 如何操作web.py自带的webserver的日志? 解法 我们可以用wsgilog来操作内置的webserver的日志,并做其为中间件加到应用中。 如下,写一个Log类继承wsgilog.WsgiLog,在_init_中把参数传给基类,如这个例子: import sys, logging from wsgilog import WsgiLog, LogIO import config c