Showing posts sorted by relevance for query maven. Sort by date Show all posts
Showing posts sorted by relevance for query maven. Sort by date Show all posts

Thursday, April 21, 2016

How to install MAVEN on Windows



Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information.

Maven addresses two aspects of building software: first, it describes how software is built, and second, it describes its dependencies. Contrary to preceding tools like Apache Ant, it uses conventions for the build procedure, and only exceptions need to be written down. An XML file describes the software project being built, its dependencies on other external modules and components, the build order, directories, and required plug-ins.

So, in other words, Maven will do the job managing your project, you just need to specify  the dependencies and it will help you building you project among other tasks, and no, it's not black magic, it's MAVEN, awesome, right?, and you know what is even better? ...it is FREE, so, Awesome X 2, =) (who doesn't like free stuff? I do)

Well, now I'm going to show you how to install Maven on your PC.

In order to install Apache Maven just download the Maven's zip file (here), and then unzip it to your local (I placed it in C:/) and proceed to configure the Windows environment variables:

Tools used:
  • JDK 1.7
  • Maven  

Install JDK, you can download it from here
Add JAVA_HOME to Windows environment variables. Right click on PC icon --> Advanced system settings --> Environment Variables





Now, download, unzip and place you Maven zip file in the folder you want (for example: C:/ )

Add M2_HOME and MAVEN_HOME environment variables:





Update PATH variable. We need to append Maven bin folder  %M2_HOME%\bin. This is going to help you run Maven's command everywhere:





Now, let's proceed to verify that we did everything fine. 
Verify Java, in command prompt type:  java -version
You should get something like this:




Now, let's verify Maven, in command prompt, type: mvn -version
If you get the next screen, you did the installation like a champ!





Now you have everything ready to start working in your Java projects using Maven and you can apply those ninja code moves you learned in YouTube. Enjoy!


Note: Just in case you didn't know, Maven 3.2 requires JDK 1.6 or above, while Maven version 3.0/3.1 requires JDK 1.5 or above.


Tuesday, October 10, 2017

Spring Boot - Hello World Standalone Application



Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
Features
  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated 'starter' POMs to simplify your Maven configuration
  • Automatically configure Spring whenever possible
  • Provide production-ready features such as metrics, health checks and externalized configuration
  • Absolutely no code generation and 
  • no requirement for XML configuration

For this project, we are going to use:
  • Eclipse IDE
  • Java 8
  • Maven
Open your Eclipse IDE and create a NEW Java Project. 
Once your Java project is created, right click on it -> Configure -> Convert to Maven..

This will "MAVENize" our newly created Java project.

Next steps:

Under 'src' folder create a package for our source files: 'com.rolandoFebrero.SpringBootQuickStart'

Now copy the next code snippet in the POM.xml


<?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>com.javainterviewpoint</groupId>
 <artifactId>SpringBootTutorial</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>1.5.1.RELEASE</version>
 </parent>
 
 <dependencies>
   <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
 </dependencies>
 
 <build>
  <pluginManagement>
   <plugins>
     <plugin>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-maven-plugin</artifactId>
     </plugin>
   </plugins>
    </pluginManagement>
 </build>  
 
 </project>


If we pay attention to the POM.xml, we can see spring-boot-starter-parent and spring-boot-starter-web. 

spring-boot-starter-parent: It provides useful Maven defaults.
spring-boot-starter-web: This will add additional dependencies such Tomcat, Jackson, Spring boot etc which are required for our application.
Now let's proceed to create a Java class 'HelloWorld.java' under 'com.rolandoFebrero.SpringBootQuickStart' package.

Paste the next code snippet in 'HelloWorld.java'



package com.rolandoFebrero.SpringBootQuickStart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * 
 * @author Rolando 'rOLo' Febrero
 * @Project Spring Boot Quick Start by rOlo
 */

@RestController
@EnableAutoConfiguration
public class HelloWorld {

    @RequestMapping("/")
    String hello() {
        return "Hello World! Congratulations, you just created your Spring Boot application";
    }
    
    @RequestMapping("/hello/{name}")
    String helloThere(@PathVariable String name) {
        return "Hello, " + name + "!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(HelloWorld.class, args);
    }
}


In 'HelloWorld.java' we are using some annotations needed to tell spring what to do with receiving the request and how to do some configuration. These are:
  • @RestController:  Tells spring to render the result back to the caller.
  • @RequestMapping:  HTTP request with the path “/” should be mapped to the hello() method
  • @EnableAutoConfiguration:  This annotation tells the Spring Boot to configure the application based on the dependencies added. Since spring-boot-starter-web has added Tomcat and Spring MVC, auto-configuration will setup a web based application.

Our main method in 'HelloWorld.java' contains 'SpringApplication.run(HelloWorld.class, args)' . This is needed because Application.run() starts the whole Spring Framework and starts the tomcat server. As you can see we are passing 'HelloWorld.class' as parameter.

If you follow the steps above, your project should lool like this:




At this point we are pretty much done with the code. Now we can run our app. 
Since we are using Maven in our project, let's add the configuration to it. 

Right click on POM.xml -> Run as -> Run Configurations... (Since this is the first time running it, we need to configure how we want to run our project)

In 'Goals' type: spring-boot:run





Click on 'Run'.. you should see something similar in your console: 





 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.1.RELEASE)

2017-09-10 12:04:04.212  INFO 13016 --- [           main] c.r.SpringBootQuickStart.HelloWorld      : Starting HelloWorld on ROLO-PC with PID 13016 (D:\EclipseWorkspace\JAVA_PROJECTS\SpringBoot-Example\Spring-Boot-Example\target\classes started by rOLo in D:\EclipseWorkspace\JAVA_PROJECTS\SpringBoot-Example\Spring-Boot-Example)
2017-09-10 12:04:04.212  INFO 13016 --- [           main] c.r.SpringBootQuickStart.HelloWorld      : No active profile set, falling back to default profiles: default
2017-09-10 12:04:04.243  INFO 13016 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2b93019c: startup date [Sun Sep 10 12:04:04 EDT 2017]; root of context hierarchy
2017-09-10 12:04:04.727  INFO 13016 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration' of type [class org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-09-10 12:04:04.773  INFO 13016 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'validator' of type [class org.springframework.validation.beanvalidation.LocalValidatorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-09-10 12:04:05.145  INFO 13016 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-09-10 12:04:05.146  INFO 13016 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-09-10 12:04:05.146  INFO 13016 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.11
2017-09-10 12:04:05.228  INFO 13016 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-09-10 12:04:05.228  INFO 13016 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 985 ms
2017-09-10 12:04:05.350  INFO 13016 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-10 12:04:05.350  INFO 13016 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-10 12:04:05.350  INFO 13016 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-10 12:04:05.350  INFO 13016 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-10 12:04:05.350  INFO 13016 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-10 12:04:05.547  INFO 13016 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2b93019c: startup date [Sun Sep 10 12:04:04 EDT 2017]; root of context hierarchy
2017-09-10 12:04:05.580  INFO 13016 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.rolandoFebrero.SpringBootQuickStart.HelloWorld.hello()
2017-09-10 12:04:05.580  INFO 13016 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/{name}]}" onto java.lang.String com.rolandoFebrero.SpringBootQuickStart.HelloWorld.helloThere(java.lang.String)
2017-09-10 12:04:05.580  INFO 13016 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-09-10 12:04:05.580  INFO 13016 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-09-10 12:04:05.611  INFO 13016 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-10 12:04:05.611  INFO 13016 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-10 12:04:05.642  INFO 13016 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-10 12:04:05.722  INFO 13016 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-09-10 12:04:05.770  INFO 13016 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-09-10 12:04:05.770  INFO 13016 --- [           main] c.r.SpringBootQuickStart.HelloWorld      : Started HelloWorld in 1.946 seconds (JVM running for 5.474)


Open you browser go to : “http://localhost:8080”

You shoud see: 'Hello World! Congratulations, you just created your Spring Boot application'




Also, if you hit: http://localhost:8080/hello/Rolando (with your name as parameter) you should see :

Hello, Rolando!





You can download the complete project from my GitHub account:

https://github.com/rolando-febrero/Spring-Boot-QuickStart





*NOTE: In case you are trying to start your app and get the next error:


***************************
APPLICATION FAILED TO START
***************************

Description:

The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the connector may be misconfigured.

Action:

Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.

it is because the server is still running in the background and doesn't let your app start again using the same port. Basically you just need to stop it and run it again. Using command line :

C:\> netstat -ano | find "8080"

it returns with:
TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       1896

Now just let's kill the process:
C:\> taskkill /F /PID 1896





Programming thought of the day:


  • Moses had the first tablet that could connect to the cloud


Thursday, June 8, 2017

What is an Integration Test ?


What is an Integration Test ?

Sometimes there is not a clear distinction on what is an integration test and what is a unit test.

My basic rule of thumb is that if
  • a test uses the database
  • a test uses the network
  • a test uses an external system (e.g. a queue or a mail server)
  • a test reads/writes files or performs other I/O

…then it is an integration test and not a unit test. I have seen several developers who talk about “tests” and either they mean both or just integration tests. Here is also a brief comparison between the two.

Unit testIntegration test
Results depends only on Java codeResults also depends on external systems
Easy to write and verifySetup of integration test might be complicated
A single class/unit is tested in isolationOne or more components are tested
All dependencies are mocked if neededNo mocking is used (or only unrelated components are mocked)
Test verifies only implementation of codeTest verifies implementation of individual components and their interconnection behaviour when they are used together
A unit test uses only JUnit/TestNG and a mocking frameworkAn integration test can use real containers and real DBs as well as special integration testings frameworks (e.g. Arquillian or DbUnit)
Mostly used by developersIntegration tests are also useful to QA, DevOps, Help Desk
A failed unit test is always a regression (if the business has not changed)A failed integration test can also mean that the code is still correct but the environment has changed
Unit tests in an Enterprise application should last about 5 minutesIntegration tests in an Enterprise application can last for hours
You should now know the difference between the two....well, I hope so =)

How to write an integration test

Writing an integration test is heavily dependent on your environment. The first thing that you should decide is the scope of your integration test. So, let's say we are building a huge RESERVATION SYSTEM, we could write integration tests for:
  • Verifying correct integration of the RESERVATION SYSTEM with the printer (in a staging environment of course)
  • Verifying correct integration of this RESERVATION SYSTEM with the mail server
  • Verifying correct reading/writing of invoices from/to the DB
  • Verifying the whole data flow of receiving an order, creating an invoice, saving it to the DB and mailing it to the client. This is an End-To-End integration test
Since some of the integration tests in the case of this RESERVATION SYSTEM, use a staging environment (e.g. the mail server) it is also important to document these dependencies so that his fellow developers know about them. I always hate it when I run the test suite on a new application and half the tests fail because my workstation has no network access to the testing database!

A second point with integration tests that must be accounted is the use of detailed logging. When a unit test fails it is very easy to understand why since the scope is very narrow. When an integration test fails, things are not so simple. Because by definition an integration tests is based on many components and a specific data flow, identifying the failure cause is not always straightforward.

My recommended way to alleviate this problem, is the use of detailed logging statements (that are always needed in an Enterprise application regardless of unit tests). This way, when an integration test fails you can examine the logs and understand if the issue is in the code or in an external resource used by the test.



Why integration tests should NEVER run together with unit tests


Now we reach the most important point regarding unit tests. In a big enterprise application integration and unit tests MUST be handled differently. Here is an all too common scenario that I have personally seen multiple times.

Some developer has created a lot of unit and integration tests. All of them are executed by Maven when the test goal is run. However during a server migration some of the integration tests stop working. However everyone on the team is busy and nobody fixes the IPs in the configuration files.

Soon after some integration tests that depend on an external system run really slowly. But nobody has time to investigate the cause. Developers no longer run tests before committing code because the test suite is very slow. More unit tests break as a result, since developers do not maintain them.

New developers come into the team. They start working on the RESERVATION SYSTEM and soon find out that half the test suite is broken. Most of them do not even bother with unit tests anymore.

A valiant developer comes into the team and says that this madness must stop. He spends a day and finds out that the effort required to fix all tests is not realistic for the current time-frame. He also finds out that in several cases the unit tests are broken because of changes in the business requirements. So fixings the tests is not a straightforward process since somebody has to adapt them to new code.

By this point it is clear that tests are not actually used in this project. New developers simply declare that “writing unit tests is a waste of time” and they are right from their point of view, since nobody wants to work with a broken test suit.

This is a scenario that we need to avoid!


Delegating integration tests to Maven Failsafe plugin


There are many ways to split unit and integration tests. My suggestion is to use the Maven failsafe plugin.

Unit tests should follow the naming convention introduced in the first part of this series. Unit test classes are named with “name of class + Test”. Then they are placed in the test directory of the Maven project structure.

The unit tests are executed automatically when the test goal is run.

Next you should add the failsafe plugin in your pom.xml file.

<project><build>
    <plugins><plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-failsafe-plugin</artifactId>
        <version>2.13</version>
        <executions>
          <execution>
            <id>integration-test</id>
            <goals>
              <goal>integration-test</goal>
            </goals>
          </execution>
          <execution>
            <id>verify</id>
            <goals>
              <goal>verify</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


Your integration tests however have a different naming convention. They are named as “name of class + IT”. IT stands for Integration Test.

Now the test goal will ignore them. Instead these tests will be executed by the integration-test goal which is a built-in goal into Maven. Here is a table that summarizes this split

Unit testsIntegration Tests
Located inMaven test directoryMaven test directory
Naming conventionname of class + Testname of class + IT
Example class nameBasketWeightTest.javaInvoicingProcessorIT.java
Managed byMaven surefire pluginMaven failsafe plugin
Executed in test goalYesNo
Executed in integration-test goalNoYes


How to run integration tests in your build process


Now that all these changes are done you have great flexibility on how you run unit tests. Most importantly your build server (e.g. Jenkins) should contain a mixture of jobs that deal with both kinds of tests. Here is a overview of suggested jobs.

Job typeScheduleDescriptionTests
Main buildEvery 15 minutes or half hour.Only compiles and runs unit tests. Should finish in 15-20 minutes maxOnly unit tests
Integration buildEvery 24 hours (usually at night)Runs integrations tests. Can run for 2-3 hoursAll tests
QA buildManuallyDeploys to a QA environmentAll tests

The suggested workflow is the following
  1. Developers run the test goal during development
  2. Developers run the test goal before any commit
  3. Developers run the integration-test goal before a major commit with many side effects
  4. Build server compiles code and runs the test goal every 15-30 minutes (main build)
  5. Build server compiles code and runs the integration-test goal every day (integration build)
  6. Build server compiles code and runs the integration-test goal before a release to QA
With this workflow it is clear that developers get fast feedback from the unit tests so anything that breaks can be fixed immediately. The boring process of running integration tests is left to the build server which runs them automatically in a well defined schedule.


Conclusion


In this post we have finally tackled integration tests. We showed you the differences with unit tests regarding test focus, external systems and running time.

We also hope we convinced you that they must be handled differently. Our suggested method for splitting tests is the maven failsafe plugin.

Finally we proposed some combinations of build jobs and how they run different types of tests.

Feel free to post your suggestions below regarding unit and integration tests.




Programming thought of the day:
  • Me: Siri, why am I alone? 
  • Siri: *opens front facing camera*


Friday, January 27, 2017

log4j with maven and Java - Project Example


log4j is a reliable, fast and flexible logging framework (APIs) written in Java, which is distributed under the Apache Software License. log4j is a popular logging package written in Java. log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.

This utility will help you to keep track of everything your code does (and the government will keep track of everything you do in your life, just kidding -__-). Well, I'm going to show a short but solid example on how to use log4j. In this project we are going to log everything into a text file.

For this exercise we are going to use:
  • Java 1.7
  • Maven
  • log4j
  • Eclipse IDE

First of all, let's create a Maven project in Eclipse. (if you don't know how to install Maven in your PC, please go here)



Select option "Create a simple project"





Then fill all the fields according the bellow image. Here we are putting the info needed for our pom.xml




When done with these settings, open your pom.xml file and add the next lines:



        <properties>
  <jdk.version>1.7</jdk.version>
  <log4j.version>1.2.17</log4j.version>
 </properties>

 <dependencies>

  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>${log4j.version}</version>
  </dependency>

 </dependencies> 



Your pom.xml should look like this:




What we just did, was add some dependencies to our project, so with the help of mighty Maven, we are going to install them. Right click on pom.xml and select "Maven install"... Maven will pull all the jars needed (to your .M2 reposotory), in this case log4j






You should get a "BUILD SUCCESS" message in your console:





Log4j needs some properties file in which we specify its configuration. Let's create a "log4j.properties" file and added to our project:






Once created, double click on it, and add the following code:



# Root logger option
log4j.rootLogger=ERROR, stdout, file
log4j.rootLogger=INFO, stdout, file
# Redirect log messages to console 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 # Rirect log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=D:\\log4j-application.log log4j.appender.file.MaxFileSize=5MB log4j.appender.file.MaxBackupIndex=10 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


Here we are specifying how and where to append the logs. Take a look at those lines and change accordingly.


Now we are going to proceed to write our code. Create a class and let's name it "HelloExample.java", here is the code:



package com.rolandoFebrero;

import org.apache.log4j.Logger;

public class HelloExample {
 
 final static Logger logger = Logger.getLogger(HelloExample.class);

 public static void main(String[] args) {
  
  HelloExample obj = new HelloExample();
  obj.runMe("Log4j Example");
  
 }
 
 private void runMe(String parameter){
  
  if(logger.isDebugEnabled()){
   logger.debug("This will be logged as DEBUG : " + parameter);
  }
  
  if(logger.isInfoEnabled()){
   logger.info("This will be logged as INFO : " + parameter);
  }
  
  logger.warn("This will be logged as WARN : " + parameter);
  logger.error("This will be logged as ERROR : " + parameter);
  logger.fatal("This will be logged as FATAL: " + parameter);
  
 }
 
}



now, create another class, this time let's name it "HelloExampleException.java". Here is the code:


package com.rolandoFebrero;

import org.apache.log4j.Logger;

public class HelloExampleException {

final static Logger logger = Logger.getLogger(HelloExampleException.class);
 
 public static void main(String[] args) {
 
  HelloExampleException obj = new HelloExampleException();
  
  try{
   obj.divide();
  }catch(ArithmeticException ex){
   logger.error("Something wrong!!!, you are getting an exception ", ex);
  }
  
  
 }
 
 private void divide(){
  
  int i = 3 / 0;

 } 
}



If you look at the code, in our first class, HelloExample.java, we are just printing a message, but with different log levels, such as debug, info, warn, error, fatal. This helps us to identify the kind of message we want to log. On the other file, HelloExampleExceptio.java, we are performing some math operation. In the main method we are making a call to "divide()". This divide() method just performs one single math operation, which is "3 / 0". Obviously, we can't divide a number by zero, so we will get an exception, in this specific case, an Arithmetic exception. I did that on purpose so we can see how an exception is logged by log4j.

Now, just right click on either HelloExample.java or HelloExampleExceptio.java; you might see the message in you console. Then go to where "log4j-application.log" file is located (hint: specified in log4j.properties) and there you'll find all the logs...


If you want to download the code for this project just go to my github account:

https://github.com/rolando-febrero/log4j-maven-Example.git




Programming thought of the day:


  • If at first you don’t succeed; call it version 1.0.