0

Basically I have a normal Java app, with a main. I use Intelij Ultimate. I have the following pom

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <groupId>88</groupId>
    <artifactId>SpaceX</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901.jdbc4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/aspectj/aspectjrt -->
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.4</version>
        </dependency>



    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

So I also have a LoggingAspect which I just cant figure out how to run. I tried this too http://confluence.jetbrains.com/display/~roman.shevchenko/AspectJ+Support+Plugin

And manually downloaded the jar but I also downloaded the Intelij plugins for Aspects. Like AspectJ Support and Spring Aspect.

My aspect class looks like this:

public aspect LoggingAspect {
    pointcut tracing():call(public * com.company..*.*(..)) && !within(LoggingAspect);

    private Logger logger= Logger.getLogger("com.company");

    public LoggingAspect() {
        PropertyConfigurator.configure("logging.properties");
    }

    before(): tracing(){
        logger.info("Entering: "+ thisJoinPointStaticPart.getSignature());
    }

    after():tracing(){
        logger.info("Exiting: "+ thisJoinPointStaticPart.getSignature());
    }
}

As you can see. I want to use the java.util.logging.Logger and I have a logging.properties file where I set up the output file. I tried compiling the app like in the link I pasted above, running the app normally, nothing seems to be working. My aspect is not working at all/ it's not being used. Any advice? Am I missing something?

I dont want to use Spring Aspect with annotations yet. I can't figure out how to make this one work first

I changed my compiler to ajc and tested the connection, everything is fine. I have added Aspectjrt to dependencies... it still doesn't do anything when I try to run the program. It just runs normaly without applying the aspects. Any ideas?

kriegaex
  • 63,017
  • 15
  • 111
  • 202
Mocktheduck
  • 1,333
  • 1
  • 22
  • 43
  • Do you want to use compile- or load-time weaving? My answer depends on yours. And just another quick question to verify: AspectJ is a new topic for you, I assume? – kriegaex Apr 02 '17 at 10:55
  • Yes, it's a new topic and I can't find any good materials to read up on. I want to run my program and also get the logs in the file as I run the app. I assume I want load-time weaving right? – Mocktheduck Apr 02 '17 at 12:08
  • There is a lot of good material out there. Why not start with with the [AspectJ documentation](https://eclipse.org/aspectj/docs.php) and, if you plan to use Maven to build your product via compile-time weaving, the [AspectJ Maven plugin documentation](http://www.mojohaus.org/aspectj-maven-plugin/). As you seem to be unsure about it, I recommend CTW, not LTW. If you agree, I can provide a sample Maven POM in order to get your sample code running. – kriegaex Apr 02 '17 at 15:07
  • If it can make my code running, that'd be great. I also tried Hello world greeting samples and still had no results because most of the examples use Eclipse. – Mocktheduck Apr 02 '17 at 15:09

1 Answers1

1

This is a solution for compile-time weaving. Because all major IDEs can import and update projects from Maven, it works in Eclipse, IntelliJ IDEA and probably also NetBeans (never tried).

Maven POM:

<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>

  <groupId>88</groupId>
  <artifactId>SpaceX</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.source-target.version>1.8</java.source-target.version>
    <aspectj.version>1.8.10</aspectj.version>
  </properties>

  <build>

    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.5.1</version>
          <configuration>
            <source>${java.source-target.version}</source>
            <target>${java.source-target.version}</target>
            <!-- IMPORTANT -->
            <useIncrementalCompilation>false</useIncrementalCompilation>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>aspectj-maven-plugin</artifactId>
          <version>1.10</version>
          <configuration>
            <!--<showWeaveInfo>true</showWeaveInfo> -->
            <source>${java.source-target.version}</source>
            <target>${java.source-target.version}</target>
            <Xlint>ignore</Xlint>
            <complianceLevel>${java.source-target.version}</complianceLevel>
            <encoding>${project.build.sourceEncoding}</encoding>
            <!--<verbose>true</verbose> -->
            <!--<warn>constructorName,packageDefaultMethod,deprecation,maskedCatchBlocks,unusedLocals,unusedArguments,unusedImport</warn> -->
          </configuration>
          <executions>
            <execution>
              <!-- IMPORTANT -->
              <phase>process-sources</phase>
              <goals>
                <goal>compile</goal>
                <goal>test-compile</goal>
              </goals>
            </execution>
          </executions>
          <dependencies>
            <dependency>
              <groupId>org.aspectj</groupId>
              <artifactId>aspectjtools</artifactId>
              <version>${aspectj.version}</version>
            </dependency>
            <dependency>
              <groupId>org.aspectj</groupId>
              <artifactId>aspectjweaver</artifactId>
              <version>${aspectj.version}</version>
            </dependency>
          </dependencies>
        </plugin>
      </plugins>
    </pluginManagement>

    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>aspectj-maven-plugin</artifactId>
      </plugin>
    </plugins>

  </build>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${aspectj.version}</version>
      </dependency>
      <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.1-901.jdbc4</version>
      </dependency>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
      </dependency>
      <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
      </dependency>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
      </dependency>
  </dependencies>

</project>

Log4J config file:

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Driver application:

package com.company.app;

public class Application {
  public static void main(String[] args) {
    new Application().doSomething("foo", 11);
  }

  public String doSomething(String string, int i) {
    return "blah";
  }
}

Improved aspect:

The way you load logging.properties only works from within a JAR, but not when running code from your IDE. I suggest you rely on the classpath being correctly imported from the Maven project, putting the config file under src/main/resources and then opening it via ClassLoader.getResourceAsStream(..).

package com.company.aspect;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public aspect LoggingAspect {
  private static final Logger logger = Logger.getLogger("com.company");

  public LoggingAspect() {
    PropertyConfigurator.configure(
      Thread
        .currentThread()
        .getContextClassLoader()
        .getResourceAsStream("logging.properties")
    );
  }

  pointcut tracing() :
    call(public * com.company..*.*(..)) &&
    !within(LoggingAspect);

  before() : tracing() {
    logger.info("Entering: " + thisJoinPointStaticPart.getSignature());
  }

  after() : tracing() {
    logger.info("Exiting: " + thisJoinPointStaticPart.getSignature());
  }
}

Console log:

2017-04-02 17:58:06 INFO  company:23 - Entering: String com.company.app.Application.doSomething(String, int)
2017-04-02 17:58:06 INFO  company:27 - Exiting: String com.company.app.Application.doSomething(String, int)
kriegaex
  • 63,017
  • 15
  • 111
  • 202
  • still nothing. I don't get it. I use the java.util.logging. It doesn't use the aspects – Mocktheduck Apr 02 '17 at 18:30
  • I did everything you mentioned. Am I just supposed to run the program normally?Cause Im doing it and it's still not working – Mocktheduck Apr 02 '17 at 22:12
  • Is this some kind of joke? You are really annoying me: You have shown me a POM and aspect code using Log4J and now you say you are using Java logging? Why did you make me do the work to fix your Log4J setup then? Just copy & paste my whole code and put everything into the right Maven directories, then import a new project from those sources and be happy. If you dislike Log4J you can still use `System.out.println` or whatever you prefer. I am out of here, I do not like wasting my time with people who cannot make up their minds what they want. My sample code works with Eclipse and IDEA. Bye now. – kriegaex Apr 02 '17 at 22:29