You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by pk...@apache.org on 2024/06/14 09:21:44 UTC

(logging-log4j-samples) branch main updated: Add AspectJ example

This is an automated email from the ASF dual-hosted git repository.

pkarwasz pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/logging-log4j-samples.git


The following commit(s) were added to refs/heads/main by this push:
     new 8a02e7c  Add AspectJ example
8a02e7c is described below

commit 8a02e7c0fa115d62b030255ce2b6f6d106456fbd
Author: Piotr P. Karwasz <pi...@karwasz.org>
AuthorDate: Fri Jun 14 11:18:08 2024 +0200

    Add AspectJ example
    
    Adds an example on how to use AspectJ to perform trace logging with
    Log4j API.
---
 log4j-samples-aspectj/pom.xml                      | 65 +++++++++++++++++
 .../log4j2/samples/aspectj/GreeterService.java     | 21 ++++++
 .../log4j2/samples/aspectj/GreeterServiceImpl.java | 32 +++++++++
 .../log4j2/samples/aspectj/LoggingAspect.java      | 84 ++++++++++++++++++++++
 .../logging/log4j2/samples/aspectj/Main.java       | 50 +++++++++++++
 .../src/main/resources/application.yml             |  3 +
 .../src/main/resources/log4j2.xml                  | 35 +++++++++
 log4j-samples-graalvm/pom.xml                      | 26 ++++---
 pom.xml                                            |  1 +
 9 files changed, 309 insertions(+), 8 deletions(-)

diff --git a/log4j-samples-aspectj/pom.xml b/log4j-samples-aspectj/pom.xml
new file mode 100644
index 0000000..380de25
--- /dev/null
+++ b/log4j-samples-aspectj/pom.xml
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one or more
+  ~ contributor license agreements.  See the NOTICE file distributed with
+  ~ this work for additional information regarding copyright ownership.
+  ~ The ASF licenses this file to you under the Apache License, Version 2.0
+  ~ (the "License"); you may not use this file except in compliance with
+  ~ the License.  You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.apache.logging.log4j.samples</groupId>
+    <artifactId>log4j-samples</artifactId>
+    <version>${revision}</version>
+  </parent>
+
+  <artifactId>log4j-samples-aspectj</artifactId>
+  <name>Apache Log4j Samples: AspectJ example</name>
+  <description>Example of Log4j trace logging using AspectJ</description>
+
+  <properties>
+    <!-- Used by Spring Boot starters -->
+    <log4j2.version>${log4j.version}</log4j2.version>
+  </properties>
+
+  <dependencies>
+
+    <dependency>
+      <groupId>org.apache.logging.log4j</groupId>
+      <artifactId>log4j-api</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>org.springframework.boot</groupId>
+      <artifactId>spring-boot-starter</artifactId>
+      <exclusions>
+        <exclusion>
+          <groupId>org.springframework.boot</groupId>
+          <artifactId>spring-boot-starter-logging</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+
+    <dependency>
+      <groupId>org.springframework.boot</groupId>
+      <artifactId>spring-boot-starter-aop</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>org.springframework.boot</groupId>
+      <artifactId>spring-boot-starter-log4j2</artifactId>
+      <scope>runtime</scope>
+    </dependency>
+
+  </dependencies>
+</project>
diff --git a/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/GreeterService.java b/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/GreeterService.java
new file mode 100644
index 0000000..d0ed6cb
--- /dev/null
+++ b/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/GreeterService.java
@@ -0,0 +1,21 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.logging.log4j2.samples.aspectj;
+
+public interface GreeterService {
+    void greet(String name);
+}
diff --git a/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/GreeterServiceImpl.java b/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/GreeterServiceImpl.java
new file mode 100644
index 0000000..3fbd631
--- /dev/null
+++ b/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/GreeterServiceImpl.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.logging.log4j2.samples.aspectj;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+@Component
+public class GreeterServiceImpl implements GreeterService {
+
+    private final Logger logger = LogManager.getLogger();
+
+    @Override
+    public void greet(final String name) {
+        logger.info("Hello {}!", name);
+    }
+}
diff --git a/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/LoggingAspect.java b/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/LoggingAspect.java
new file mode 100644
index 0000000..5d15ece
--- /dev/null
+++ b/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/LoggingAspect.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.logging.log4j2.samples.aspectj;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.message.DefaultFlowMessageFactory;
+import org.apache.logging.log4j.message.FlowMessageFactory;
+import org.apache.logging.log4j.spi.AbstractLogger;
+import org.aspectj.lang.JoinPoint;
+import org.aspectj.lang.annotation.AfterReturning;
+import org.aspectj.lang.annotation.AfterThrowing;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Before;
+import org.aspectj.lang.annotation.Pointcut;
+import org.aspectj.lang.reflect.SourceLocation;
+import org.springframework.stereotype.Component;
+
+@Aspect
+@Component
+public class LoggingAspect {
+
+    private static final Logger LOGGER = LogManager.getLogger();
+    private static final FlowMessageFactory FLOW_MESSAGE_FACTORY = new DefaultFlowMessageFactory();
+
+    private static StackTraceElement getLocation(final JoinPoint joinPoint) {
+        final SourceLocation location = joinPoint.getSourceLocation();
+        final String methodName = joinPoint.getSignature().getName();
+        String fileName = null;
+        try {
+            fileName = location.getFileName();
+        } catch (final Exception e) {
+            LOGGER.debug("Failed to get the file name from the source location.", e);
+        }
+        int lineNumber = -1;
+        try {
+            lineNumber = location.getLine();
+        } catch (final Exception e) {
+            LOGGER.debug("Failed to get the line number from the source location.", e);
+        }
+        return new StackTraceElement(location.getWithinType().getName(), methodName, fileName, lineNumber);
+    }
+
+    @Pointcut("within(org.apache.logging.log4j2.samples.aspectj.*)")
+    public void traceLogging() {}
+
+    @Before("traceLogging()")
+    public void traceEntry(final JoinPoint jp) {
+        LOGGER.atTrace()
+                .withMarker(AbstractLogger.ENTRY_MARKER)
+                .withLocation(getLocation(jp))
+                .log(FLOW_MESSAGE_FACTORY.newEntryMessage(null, jp.getArgs()));
+    }
+
+    @AfterReturning(pointcut = "traceLogging()", returning = "response")
+    public void logMethodResponse(final JoinPoint jp, final Object response) {
+        LOGGER.atTrace()
+                .withMarker(AbstractLogger.EXIT_MARKER)
+                .withLocation(getLocation(jp))
+                .log(FLOW_MESSAGE_FACTORY.newExitMessage(null, response));
+    }
+
+    @AfterThrowing(pointcut = "traceLogging()", throwing = "exception")
+    public void logMethodException(final JoinPoint jp, final Throwable exception) {
+        LOGGER.atError()
+                .withMarker(AbstractLogger.THROWING_MARKER)
+                .withLocation(getLocation(jp))
+                .log("Throwing", exception);
+    }
+}
diff --git a/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/Main.java b/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/Main.java
new file mode 100644
index 0000000..8047d4d
--- /dev/null
+++ b/log4j-samples-aspectj/src/main/java/org/apache/logging/log4j2/samples/aspectj/Main.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.logging.log4j2.samples.aspectj;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+
+@SpringBootApplication
+@EnableAspectJAutoProxy
+public class Main implements CommandLineRunner {
+
+    private final Logger logger = LogManager.getLogger();
+
+    public static void main(final String[] args) {
+        SpringApplication.run(Main.class, args);
+    }
+
+    private GreeterService greeterService;
+
+    @Autowired
+    public void setGreeterService(final GreeterService greeterService) {
+        this.greeterService = greeterService;
+    }
+
+    @Override
+    public void run(final String... args) {
+        final String who = args.length > 0 ? args[0] : "AspectJ";
+        logger.info("Calling greeter service with parameter {}", who);
+        greeterService.greet(who);
+    }
+}
diff --git a/log4j-samples-aspectj/src/main/resources/application.yml b/log4j-samples-aspectj/src/main/resources/application.yml
new file mode 100644
index 0000000..c1d1f3e
--- /dev/null
+++ b/log4j-samples-aspectj/src/main/resources/application.yml
@@ -0,0 +1,3 @@
+spring:
+  aop:
+    proxy-target-class: false
\ No newline at end of file
diff --git a/log4j-samples-aspectj/src/main/resources/log4j2.xml b/log4j-samples-aspectj/src/main/resources/log4j2.xml
new file mode 100644
index 0000000..790b13b
--- /dev/null
+++ b/log4j-samples-aspectj/src/main/resources/log4j2.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one or more
+  ~ contributor license agreements.  See the NOTICE file distributed with
+  ~ this work for additional information regarding copyright ownership.
+  ~ The ASF licenses this file to you under the Apache License, Version 2.0
+  ~ (the "License"); you may not use this file except in compliance with
+  ~ the License.  You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+<Configuration xmlns="https://logging.apache.org/xml/ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+               xsi:schemaLocation="
+                   https://logging.apache.org/xml/ns
+                   https://logging.apache.org/xml/ns/log4j-config-2.xsd">
+    <Appenders>
+        <Console name="CONSOLE">
+            <PatternLayout pattern="%d [%t] %p %C:%M - %m%n"/>
+        </Console>
+    </Appenders>
+    <MarkerFilter marker="FLOW"
+                  onMatch="ACCEPT"
+                  onMisMatch="NEUTRAL"/>
+    <Loggers>
+        <Root level="INFO">
+            <AppenderRef ref="CONSOLE"/>
+        </Root>
+    </Loggers>
+</Configuration>
diff --git a/log4j-samples-graalvm/pom.xml b/log4j-samples-graalvm/pom.xml
index ee9ee84..4b68efd 100644
--- a/log4j-samples-graalvm/pom.xml
+++ b/log4j-samples-graalvm/pom.xml
@@ -31,18 +31,10 @@
   </properties>
 
   <dependencies>
-
     <dependency>
       <groupId>org.apache.logging.log4j</groupId>
       <artifactId>log4j-api</artifactId>
     </dependency>
-
-    <dependency>
-      <groupId>org.apache.logging.log4j</groupId>
-      <artifactId>log4j-core</artifactId>
-      <scope>runtime</scope>
-    </dependency>
-
   </dependencies>
 
   <build>
@@ -90,4 +82,22 @@
 
     </plugins>
   </build>
+
+  <profiles>
+    <profile>
+      <id>use-log4j-core</id>
+      <activation>
+        <activeByDefault>true</activeByDefault>
+      </activation>
+
+      <dependencies>
+        <dependency>
+          <groupId>org.apache.logging.log4j</groupId>
+          <artifactId>log4j-core</artifactId>
+          <scope>runtime</scope>
+        </dependency>
+      </dependencies>
+
+    </profile>
+  </profiles>
 </project>
diff --git a/pom.xml b/pom.xml
index 02288a0..6626143 100644
--- a/pom.xml
+++ b/pom.xml
@@ -34,6 +34,7 @@
   <name>Apache Log4j Samples</name>
 
   <modules>
+    <module>log4j-samples-aspectj</module>
     <module>log4j-samples-asynclogger</module>
     <module>log4j-samples-configuration</module>
     <module>log4j-samples-flume-common</module>