What I am going to do here is create a simple HelloWorld application with a few lines which get logged using Apache-commons logging facade and Log4J providing the actual logging implementation. The sample assumes that you have JDK 1.7+ and Gradle installed correctly on your system.
My working directory will be /home/siddharth/Temp/GradleTest. All files and folders mentioned will be created within this directory. For this project, I will use the standard folder structure required by Gradle. The following folders need to be created under GradleTest:
GradleTest +- src +- main +- java +- resources
Let's create the build.gradle file under GradleTest directory which will be used by Gradle to build the project. The contents of this file is:
apply plugin: 'java' repositories{ mavenCentral() } dependencies { compile 'log4j:log4j:1.2.17' compile 'commons-logging:commons-logging:1.2' } jar { from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } manifest { attributes 'Main-Class': 'Sample' } }
The java-plugin supports a number of tasks which are mentioned here. Now that we have the instructions for gradle ready lets create the HelloWorld program.
Create a file named 'Sample.java' within GradleTest/src/main/java. The content of this file is:
import java.lang.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class Sample { final static Log logger = LogFactory.getLog(Sample.class); public static void main(String[] args) { logger.debug("main start"); System.out.println("Hello Siddharth"); logger.debug("main end"); } }
Create a text file named 'log4j.properties' in the GradleTest/src/main/resources directory. This file is used to configure the behavior of Log4J. The content of this file is below:
# Root logger option log4j.rootLogger=DEBUG, stdout, file # Redirect log messages # Redirect log messages to a log file, support file rolling. log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=$HOME log4j.appender.file.MaxFileSize=5We are now all set to build the project. Open a terminal window (command prompt in Windows). Navigate to the GradleTest folder, for me this is /home/siddharth/Temp/GradleTest. Type in:
gradle assemble
This will build the project. Since we have mentioned Apache-commons and Log4J as dependencies, these will be downloaded as part of the build process; you'll need to be connected to the WWW. The output of the build process should look something like this:
Lets now test if everything got built as it should have by running the code. While in the GradleTest directory, type in:
> java -cp build/libs -jar build/libs/GradleTest.jar
You should see the output of the program.
