gpt4 book ai didi

java - 使用 Spring 添加记录器

转载 作者:行者123 更新时间:2023-12-01 13:10:24 24 4
gpt4 key购买 nike

有没有办法用 Spring 添加记录器实例?有没有办法跟踪我的自定义代码中的每个方法调用?

我通常这样做:

package my.java.code;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class A {
// How to add this line with Spring ?
private static final Logger logger = LoggerFactory.getLogger(A.class);
public void A() {
// How to add this line with Spring ?
logger.trace("");
// Do something...
}
public void A(Object o) {
// How to add this line with Spring ?
logger.trace("{}", o);
// Do something...
}
public void method1() {
// How to add this line with Spring ?
logger.trace("");
// Do something...
}
public void method2(Object o) {
// How to add this line with Spring ?
logger.trace("{}", o);
// Do something...
}
}

有没有办法用 Spring 来简化这个过程?

目标是:

  • 避免重复代码

最佳答案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<bean id="customizableTraceInterceptor"
class="org.springframework.aop.interceptor.CustomizableTraceInterceptor">
<property name="enterMessage"
value="Entering $[targetClassName].$[methodName]($[argumentTypes] $[arguments])" />
<property name="exitMessage" value="Leaving $[methodName](): $[returnValue]" />
</bean>

<aop:config>
<aop:advisor advice-ref="customizableTraceInterceptor"
pointcut="execution(* fr.my.package.dao..*.*(..))" />
</aop:config>

</beans>

这帮助我跟踪 fr.my.package.dao 包中所有类的所有方法的每次调用。

感谢@m-deinum

关于java - 使用 Spring 添加记录器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22914838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com