Showing posts with label logging. Show all posts
Showing posts with label logging. Show all posts

Monday, September 29, 2014

Add library dependency for Maven

This article is about how to add library dependency for Maven, using log4j and commons-logging as example.
  1. Create basic project with maven:
     mvn archetype:generate \
     -DarchetypeArtifactId=maven-archetype-quickstart \
     -DinteractiveMode=false \
     -DgroupId=tw.com.codedata \
     -DartifactId=helloworld
    
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building Maven Stub Project (No POM) 1
     [INFO] ------------------------------------------------------------------------
     [INFO] 
     [INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>>
     [INFO] 
     [INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<
     [INFO] 
     [INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom ---
     [INFO] Generating project in Batch mode
     [INFO] ----------------------------------------------------------------------------
     [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
     [INFO] ----------------------------------------------------------------------------
     [INFO] Parameter: groupId, Value: tw.com.codedata
     [INFO] Parameter: packageName, Value: tw.com.codedata
     [INFO] Parameter: package, Value: tw.com.codedata
     [INFO] Parameter: artifactId, Value: helloworld
     [INFO] Parameter: basedir, Value: /home/linst/ws/study/maven
     [INFO] Parameter: version, Value: 1.0-SNAPSHOT
     [INFO] project created from Old (1.x) Archetype in dir: /home/linst/ws/study/maven/helloworld
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 1:46.068s
     [INFO] Finished at: Mon Sep 29 18:06:53 CST 2014
     [INFO] Final Memory: 10M/239M
     [INFO] ------------------------------------------------------------------------
    
    $ tree .
    .
    └── helloworld
        ├── pom.xml
        └── src
            ├── main
            │   └── java
            │       └── tw
            │           └── com
            │               └── codedata
            │                   └── App.java
            └── test
                └── java
                    └── tw
                        └── com
                            └── codedata
                                └── AppTest.java
    
    12 directories, 3 files
    
     
     
       4.0.0
       tw.com.codedata
       helloworld
       jar
       1.0-SNAPSHOT
       helloworld
       http://maven.apache.org
       
         
           junit
           junit
           3.8.1
           test
         
       
     
    
  2. Create file ./helloworld/src/main/resources/log4j.properties:
     $ cd helloworld/src/main/
     $ mkdir resources
     $ vim resources/log4j.properties
    
     # Set root logger level to DEBUG and have appenders A1, A2.
     log4j.rootLogger=DEBUG, A1, A2
      
     # A1 is set to be a ConsoleAppender
     log4j.appender.A1=org.apache.log4j.ConsoleAppender
     log4j.appender.A1.layout=org.apache.log4j.PatternLayout
     log4j.appender.A1.layout.ConversionPattern=[%d{yyyy/MM/dd HH:mm:ss,SSS}][%p][%C-%L] %m%n
      
     # A2 is set to be a DailyRollingFileAppender to path "./log/Log4j.log"
     log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
     log4j.appender.A2.layout=org.apache.log4j.PatternLayout
     log4j.appender.A2.layout.ConversionPattern=[%d{yyyy/MM/dd HH:mm:ss,SSS}][%p][%C-%L] %m%n
     log4j.appender.A2.File=./log/Log4j.log
    
  3. Update ./helloworld/src/main/java/tw/com/codedata/App.java to HelloWorld.java with below content:
     
     package tw.com.codedata;
      
     import org.apache.commons.logging.Log;
     import org.apache.commons.logging.LogFactory;
      
     public class HelloWorld {
      
         static Log logger = LogFactory.getLog(HelloWorld.class);
      
         public static void main(String[] args) {
      logger.info("Hello World");
         }
      
     }
    
  4. Try to build, you will get errors because no required logging libraries:
     $ cd helloworld/
     $ mvn package
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building helloworld 1.0-SNAPSHOT
     [INFO] ------------------------------------------------------------------------
     [INFO] 
     [INFO] --- maven-resources-plugin:2.3:resources (default-resources) @ helloworld ---
     [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
     [INFO] Copying 1 resource
     [INFO] 
     [INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ helloworld ---
     [INFO] Compiling 1 source file to /home/linst/ws/study/maven/helloworld/target/classes
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD FAILURE
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 0.792s
     [INFO] Finished at: Mon Sep 29 18:27:38 CST 2014
     [INFO] Final Memory: 8M/239M
     [INFO] ------------------------------------------------------------------------
     [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.0.2:compile (default-compile) on project helloworld: Compilation failure: Compilation failure:
     [ERROR] /home/linst/ws/study/maven/helloworld/src/main/java/tw/com/codedata/HelloWorld.java:[3,33] package org.apache.commons.logging does not exist
     [ERROR] 
     [ERROR] /home/linst/ws/study/maven/helloworld/src/main/java/tw/com/codedata/HelloWorld.java:[4,33] package org.apache.commons.logging does not exist
     [ERROR] 
     [ERROR] /home/linst/ws/study/maven/helloworld/src/main/java/tw/com/codedata/HelloWorld.java:[8,11] cannot find symbol
     [ERROR] symbol  : class Log
     [ERROR] location: class tw.com.codedata.HelloWorld
     [ERROR] 
     [ERROR] /home/linst/ws/study/maven/helloworld/src/main/java/tw/com/codedata/HelloWorld.java:[8,24] cannot find symbol
     [ERROR] symbol  : variable LogFactory
     [ERROR] location: class tw.com.codedata.HelloWorld
     [ERROR] -> [Help 1]
     [ERROR] 
     [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
     [ERROR] Re-run Maven using the -X switch to enable full debug logging.
     [ERROR] 
     [ERROR] For more information about the errors and possible solutions, please read the following articles:
     [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
    
  5. Update pom.xml to add two dependency:
        ... 
        
          junit
          junit
          3.8.1
          test
        
        
          commons-logging
          commons-logging
          1.1.1
        
        ... 
    
  6. Build again:
     $ mvn package
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building helloworld 1.0-SNAPSHOT
     [INFO] ------------------------------------------------------------------------
     Downloading: http://nexus-ams.tomtomgroup.com:8081/nexus/content/groups/public/log4j/log4j/1.2.16/log4j-1.2.16.pom
     Downloaded: http://nexus-ams.tomtomgroup.com:8081/nexus/content/groups/public/log4j/log4j/1.2.16/log4j-1.2.16.pom (20 KB at 11.4 KB/sec)
     Downloading: http://nexus-ams.tomtomgroup.com:8081/nexus/content/groups/public/log4j/log4j/1.2.16/log4j-1.2.16.jar
     Downloaded: http://nexus-ams.tomtomgroup.com:8081/nexus/content/groups/public/log4j/log4j/1.2.16/log4j-1.2.16.jar (471 KB at 111.6 KB/sec)
     [INFO] 
     [INFO] --- maven-resources-plugin:2.3:resources (default-resources) @ helloworld ---
     [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
     [INFO] Copying 1 resource
     [INFO] 
     [INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ helloworld ---
     [INFO] Compiling 1 source file to /home/linst/ws/study/maven/helloworld/target/classes
     [INFO] 
     [INFO] --- maven-resources-plugin:2.3:testResources (default-testResources) @ helloworld ---
     [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
     [INFO] skip non existing resourceDirectory /home/linst/ws/study/maven/helloworld/src/test/resources
     [INFO] 
     [INFO] --- maven-compiler-plugin:2.0.2:testCompile (default-testCompile) @ helloworld ---
     [INFO] Compiling 1 source file to /home/linst/ws/study/maven/helloworld/target/test-classes
     [INFO] 
     [INFO] --- maven-surefire-plugin:2.10:test (default-test) @ helloworld ---
     [INFO] Surefire report directory: /home/linst/ws/study/maven/helloworld/target/surefire-reports
    
     -------------------------------------------------------
      T E S T S
     -------------------------------------------------------
     Running tw.com.codedata.AppTest
     Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.009 sec
    
     Results :
    
     Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    
     [INFO] 
     [INFO] --- maven-jar-plugin:2.2:jar (default-jar) @ helloworld ---
     [INFO] Building jar: /home/linst/ws/study/maven/helloworld/target/helloworld-1.0-SNAPSHOT.jar
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 7.618s
     [INFO] Finished at: Mon Sep 29 18:33:32 CST 2014
     [INFO] Final Memory: 13M/239M
     [INFO] ------------------------------------------------------------------------
    
    .
    ├── pom.xml
    ├── src
    │   ├── main
    │   │   ├── java
    │   │   │   └── tw
    │   │   │       └── com
    │   │   │           └── codedata
    │   │   │               ├── App.java~
    │   │   │               └── HelloWorld.java
    │   │   └── resources
    │   │       └── log4j.properties
    │   └── test
    │       └── java
    │           └── tw
    │               └── com
    │                   └── codedata
    │                       └── AppTest.java
    └── target
        ├── classes
        │   ├── log4j.properties
        │   └── tw
        │       └── com
        │           └── codedata
        │               └── HelloWorld.class
        ├── helloworld-1.0-SNAPSHOT.jar
        ├── maven-archiver
        │   └── pom.properties
        ├── surefire
        ├── surefire-reports
        │   ├── TEST-tw.com.codedata.AppTest.xml
        │   └── tw.com.codedata.AppTest.txt
        └── test-classes
            └── tw
                └── com
                    └── codedata
                        └── AppTest.class
    
    24 directories, 12 files
    
  7. Run:
     $ mvn exec:java -Dexec.mainClass="tw.com.codedata.HelloWorld"
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building helloworld 1.0-SNAPSHOT
     [INFO] ------------------------------------------------------------------------
     [INFO] 
     [INFO] --- exec-maven-plugin:1.3.2:java (default-cli) @ helloworld ---
     [WARNING] Warning: killAfter is now deprecated. Do you need it ? Please comment on MEXEC-6.
     [2014/09/29 18:38:01,362][INFO][tw.com.codedata.HelloWorld-11] Hello World
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 0.814s
     [INFO] Finished at: Mon Sep 29 18:38:01 CST 2014
     [INFO] Final Memory: 8M/239M
     [INFO] ------------------------------------------------------------------------
    
  8. Reference:
    http://www.codedata.com.tw/java/understanding-gradle-2-maven/ [Chinese]

Friday, September 26, 2014

Apache logging services, Apache log4j, Apache commons logging

Apache logging services


"The Apache Logging Services Project creates and maintains open-source software related to the logging of application behavior and released at no charge to the public."


Components:

Apache Log4j 2

Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x.

Apache log4php

A versatile logging framework for PHP. Originally a port of Apache log4j to PHP, it has grown to include various PHP specific features.

Apache log4net

A port of the excellent Apache log4j framework to the Microsoft .NET runtime.

Apache chainsaw

A GUI based log viewer. Chainsaw is a companion application to log4j written by members of the log4j development community.

Apache log4j

The original Apache logging framework for Java.

Apache log4cxx

Apache log4cxx is a logging framework for C++ patterned after log4j.

Apache log4j extras

Extras for log4j 1.x, like companions, receivers and more.


How to use Apache log4j 1.x: 

  1. Website:
    https://logging.apache.org/log4j/1.2/

    "With log4j it is possible to enable logging at runtime without modifying the application binary."
    "The target of the log output can be a file, an OutputStream, a java.io.Writer, a remote log4j server, a remote Unix Syslog daemon, or many other output targets."
  2. Read before start:
    https://logging.apache.org/log4j/1.2/manual.html
  3. Download:
    https://logging.apache.org/log4j/1.2/download.html
    http://ftp.tc.edu.tw/pub/Apache/logging/log4j/1.2.17/log4j-1.2.17.zip
    http://ftp.mirror.tw/pub/apache/logging/log4j/1.2.17/log4j-1.2.17.tar.gz
    Linux: "log4j-1.2.17.tar.gz"
    Windows: "log4j-1.2.17.zip"
  4. Import to Eclipse:
    Eclipse -> New Java Project "log4jTest01" -> Next -> Adding Log4j JAR file by "Libraries → Add External JARs" -> Select "log4j-1.2.17.zip" or "log4j-1.2.17.tar.gz" -> Finish.
  5. Create log4j.properties file in project src folder:
      
      # Set root logger level to DEBUG and have appenders A1, A2.
      log4j.rootLogger=DEBUG, A1, A2
    
      # A1 is set to be a ConsoleAppender
      log4j.appender.A1=org.apache.log4j.ConsoleAppender
      log4j.appender.A1.layout=org.apache.log4j.PatternLayout
      log4j.appender.A1.layout.ConversionPattern=[%d{yyyy/MM/dd HH:mm:ss,SSS}][%p][%C-%L] %m%n
    
      # A2 is set to be a DailyRollingFileAppender to path "./log/Log4j.log"
      log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
      log4j.appender.A2.layout=org.apache.log4j.PatternLayout
      log4j.appender.A2.layout.ConversionPattern=[%d{yyyy/MM/dd HH:mm:ss,SSS}][%p][%C-%L] %m%n
      log4j.appender.A2.File=./log/Log4j.log
    
      # Other usage: Enable below line to print only messages of level WARN or above in the package "log4jTest.log4jTest01".
      # log4j.logger.log4jTest.log4jTest01=WARN
    
  6. Create java package "log4jTest" and add source log4jTest01.java with class log4jTest01:
  7.   package log4jTest;
    
      import org.apache.log4j.Level;
      import org.apache.log4j.Logger;  
    
      public class log4jTest01 {
        private static Logger loggerlog4jTest01 = Logger.getLogger(log4jTest01.class);  
    
        public static void main(String[] args) {  
          // Example 1: (TRACE < DEBUG < INFO < WARN < ERROR < FATAL)
          loggerlog4jTest01.info("-------------------------------------------------");
          loggerlog4jTest01.info("Example 1: loggerlog4jTest01 will using Level setting in log4j.properties file");
          loggerlog4jTest01.trace("This is trace message.");
          loggerlog4jTest01.debug("This is debug message.");
          loggerlog4jTest01.info("This is info message.");
          loggerlog4jTest01.warn("This is warn message.");
          loggerlog4jTest01.error("This is error message.");
          loggerlog4jTest01.info("-------------------------------------------------");
    
          // Example 2: (TRACE < DEBUG < INFO < WARN < ERROR < FATAL)
          // Test two logger "com.foo" and "com.foo.Bar"
          loggerlog4jTest01.info("-------------------------------------------------");
          loggerlog4jTest01.info("Example 2: barlogger will inherit debug level from foologger");
          // get a logger instance named "com.foo"
          Logger  foologger = Logger.getLogger("com.foo");
    
          // Now set its level. Normally you do not need to set the
          // level of a logger programmatically. This is usually done
          // in configuration files.
          foologger.setLevel(Level.INFO);
          foologger.info("foologger setLevel to Level.INFO");
    
          Logger barlogger = Logger.getLogger("com.foo.Bar");
    
          // This request is enabled, because WARN >= INFO.
          foologger.warn("foologger Low fuel level.");
    
          // This request is disabled, because DEBUG < INFO.
          foologger.debug("foologger Starting search for nearest gas station.");
    
          // The logger instance barlogger, named "com.foo.Bar",
          // will inherit its level from the logger named
          // "com.foo" Thus, the following request is enabled
          // because INFO >= INFO.
          barlogger.info("barlogger Located nearest gas station.");
    
          // This request is disabled, because DEBUG < INFO.
          barlogger.debug("barlogger Exiting gas station search");
          loggerlog4jTest01.info("-------------------------------------------------");
        }  
      }
    
  8. Build and run, you will see below output in Eclipse Console window:
      [2014/09/28 17:56:35,583][INFO][log4jTest.log4jTest01-11] -------------------------------------------------
      [2014/09/28 17:56:35,588][INFO][log4jTest.log4jTest01-12] Example 1: loggerlog4jTest01 will using Level setting in log4j.properties file
      [2014/09/28 17:56:35,589][DEBUG][log4jTest.log4jTest01-14] This is debug message.
      [2014/09/28 17:56:35,590][INFO][log4jTest.log4jTest01-15] This is info message.
      [2014/09/28 17:56:35,590][WARN][log4jTest.log4jTest01-16] This is warn message.
      [2014/09/28 17:56:35,591][ERROR][log4jTest.log4jTest01-17] This is error message.
      [2014/09/28 17:56:35,591][INFO][log4jTest.log4jTest01-18] -------------------------------------------------
      [2014/09/28 17:56:35,592][INFO][log4jTest.log4jTest01-22] -------------------------------------------------
      [2014/09/28 17:56:35,595][INFO][log4jTest.log4jTest01-23] Example 2: barlogger will inherit debug level from foologger
      [2014/09/28 17:56:35,596][INFO][log4jTest.log4jTest01-31] foologger setLevel to Level.INFO
      [2014/09/28 17:56:35,597][WARN][log4jTest.log4jTest01-36] foologger Low fuel level.
      [2014/09/28 17:56:35,597][INFO][log4jTest.log4jTest01-45] barlogger Located nearest gas station.
      [2014/09/28 17:56:35,598][INFO][log4jTest.log4jTest01-49] -------------------------------------------------
    

Apache commons logging


"When writing a library it is very useful to log information. However there are many logging implementations out there, and a library cannot impose the use of a particular one on the overall application that the library is a part of."

"The Logging package is an ultra-thin bridge between different logging implementations. A library that uses the commons-logging API can be used with any logging implementation at runtime. Commons-logging comes with support for a number of popular logging implementations, and writing adapters for others is a reasonably simple task."

"Applications (rather than libraries) may also choose to use commons-logging."

How to use Apache commons logging: 


  1. Download:
    http://commons.apache.org/proper/commons-logging/download_logging.cgi
    http://ftp.twaren.net/Unix/Web/apache//commons/logging/binaries/commons-logging-1.2-bin.zip
  2. Import to both "log4j-1.2.17.jar" and "commons-logging-1.2.jar" to Eclipse.
  3. Create log4j.properties file(same as previous one) in project src folder.
  4. HelloWorld.java:
      package demo.JclTest;
    
      import org.apache.commons.logging.Log;
      import org.apache.commons.logging.LogFactory;
       
      public class HelloWorld {
        static Log logger = LogFactory.getLog(HelloWorld.class);
    
        public static void main(String[] args) {
          logger.info("Hello World");
          
          // Example 1: (TRACE < DEBUG < INFO < WARN < ERROR < FATAL)
          logger.info("-------------------------------------------------");
          logger.info("Example 1: logger will using Level setting in log4j.properties file");
          logger.trace("This is trace message.");
          logger.debug("This is debug message.");
          logger.info("This is info message.");
          logger.warn("This is warn message.");
          logger.error("This is error message.");
          logger.info("-------------------------------------------------");
        }
      }
    
  5. Build and run:
      [2014/09/28 18:29:11,645][INFO][demo.JclTest.HelloWorld-10] Hello World
      [2014/09/28 18:29:11,650][INFO][demo.JclTest.HelloWorld-13] -------------------------------------------------
      [2014/09/28 18:29:11,650][INFO][demo.JclTest.HelloWorld-14] Example 1: logger will using Level setting in log4j.properties file
      [2014/09/28 18:29:11,651][DEBUG][demo.JclTest.HelloWorld-16] This is debug message.
      [2014/09/28 18:29:11,652][INFO][demo.JclTest.HelloWorld-17] This is info message.
      [2014/09/28 18:29:11,652][WARN][demo.JclTest.HelloWorld-18] This is warn message.
      [2014/09/28 18:29:11,653][ERROR][demo.JclTest.HelloWorld-19] This is error message.
      [2014/09/28 18:29:11,653][INFO][demo.JclTest.HelloWorld-20] -------------------------------------------------