[英]How to Enforce a common log format using Spring AOP. Want to append a string e.g. service name in each logger
Tried below example but it's not working with spring.Getting err in editor like "call pointcut designator isn't supported by Spring". 在下面的示例中进行了尝试,但不适用于spring。在编辑器中获得err之类的内容,例如“ Spring不支持调用切入点指定符”。
https://dzone.com/articles/enforcing-common-log-format https://dzone.com/articles/enforcing-common-log-format
Any code example would be appreciated. 任何代码示例将不胜感激。
There are many ways to do this, here is 1. 有很多方法可以做到这一点,这里是1。
1) Create an annotation to add to classes/methods that need logging added: 1)创建一个注释以添加到需要添加日志的类/方法中:
@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecution {
}
2) Create an aspect to do the logging: 2)创建一个方面来进行日志记录:
@Aspect
@Component
public class LogAspect {
private List<String> messages = new ArrayList<>();
@Around("@annotation(hello.LogExecution)")
public Object handelLogging(ProceedingJoinPoint joinPoint) throws Throwable {
Object proceed = null;
try {
// log before
proceed = joinPoint.proceed();
// log after
}
catch (Exception e) {
// log exception
throw e;
}
return proceed;
}
}
It sounds like you don't have Aspect J correctly configured. 听起来您没有正确配置AspectJ。
See the answer to this question for the correct setup: 请参阅此问题的答案以获取正确的设置:
Spring + AspectJ weaving for java 8 using aspectj-maven-plugin 使用AspectJ-Maven-Plug为Java 8进行Spring + AspectJ编织
After that, spring should recognize your pointcuts 在那之后,春天应该认识你的切入点
The canonical way to use AspectJ from within Spring applications as described by the manual is to use AspectJ load-time weaving (LTW) . 如手册所述,在Spring应用程序中使用AspectJ的规范方法是使用AspectJ加载时编织(LTW) 。 It does not make sense to weave code into Spring or Java EE binaries and create new JARs etc., so IMO source or binary compile-time weaving is not an option if you want to target 3rd party code. 将代码织入Spring或Java EE二进制文件并创建新的JAR等是没有意义的,因此,如果要定位第三方代码,则IMO源代码或二进制编译时织法不是一种选择。 Instead, a dynamic Java weaving agent as described in the manual chapter I linked to above. 相反,我在上面的手动章节中介绍了动态Java编织代理。
Having said that, it was just a reply to the AOP-related suggestions I read about here. 话虽如此,这只是对我在这里阅读的与AOP相关的建议的答复。 It would work the way I described it, but I am happy the OP has solved his problems by means of Mapped Diagnostic Context already. 它将按照我描述的方式工作,但是我很高兴OP通过映射诊断上下文解决了他的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.