Home » Apache, Databases, Debian, Featured, Headline, Java, Mysql, Shell

DBAppender for Log4j 1.2

24 September 2009 7 Comments

Initially, DBAppender for Log4j was introduced in version 1.3 of Log4j, but this version was ABANDONED by Apache team. DBAppender is very useful when we want to send our log on a JNDI resource and not on standard JDBC or file. If you need just logging in a database for your application, then you should use JDBCAppender. If you want to log on a JNDI or Database Connection Pool the DBAppender is for you. In this post I will show you how to get, compile and quick test the DBAppender.

1. Environment
As usual, I work under Debian Sid with Java 1.6.0_16, Ant 1.7.1, but you can achieve the same results for any other distribution if you have the same java and ant versions (or closer).

2. Dependencies
2.1 Maven 2.2.1
Maven is a software project management tool and is based on project object model (pom). Is a great tool for java developers and probably this is the reason why Log4J Apache Team is using it.
Get Maven from http://maven.apache.org/download.html, unzip it and add maven binary path to system path. (I usually use /usr/local as folder for my java projects.)

[rb@randombugs]$ cd /usr/local
[rb@randombugs]$ tar -xzf apache-maven-2.2.1-bin.tar.gz
[rb@randombugs]$ export PATH=/usr/local/apache-maven-2.2.1/bin:${PATH}

Now we are ready to use Apache Maven.

2.2 Log4j
To compile DBAppender we need Log4j and it’s companions. First we will need to compile or deploy in Maven “repository” Log4j Application. If you already have the jar file you can simple add it to Apache Maven with the following command:

[rb@randombugs]$ mvn install:install-file -DgroupId=log4j -DartifactId=log4j -Dversion=1.2.16-SNAPSHOT -Dpackaging=jar -Dfile=/path/to/log4j-1.2.16-SNAPSHOT.jar

If you want to get it from SVN or Log4J companions need the latest version the your should compile Log4J.

[rb@randombugs]$ cd /usr/src
[rb@randombugs]$ svn checkout http://svn.apache.org/repos/asf/logging/log4j/trunk log4j
[rb@randombugs]$ cd log4j
[rb@randombugs]$ mvn install

Now we have Log4J installed.

2.3 Log4J Companions/Component
Log4J component is a framework from the discontinued log4j 1.3 implemented in log4j 1.2 and is needed by DBAppender. Log4J Component should be get it form sources and compiled , because, at this time, is no binary released by Apache Log4J Team.

[rb@randombugs]$ cd /usr/src
[rb@randombugs]$ svn checkout http://svn.apache.org/repos/asf/logging/log4j/companions/component/trunk apache-log4j-component
[rb@randombugs]$ cd apache-log4j-component
[rb@randombugs]$ mvn install

If at the end your get BUILD SUCCESSFUL you are ready to follow the next step.

2.4 Log4J Companions/Receivers
In Log4J receivers is DBAppender implemented. Log4J receivers are a backport from Log4J 1.3 for Log4J 1.2. Exactly like Log4J component, receivers, should be compiled and installed from sources, because Log4J Team doesn’t provide binaries.

[rb@randombugs]$ cd /usr/src
[rb@randombugs]$ svn checkout http://svn.apache.org/repos/asf/logging/log4j/companions/receivers/trunk apache-log4j-receivers
[rb@randombugs]$ cd apache-log4j-receivers
[rb@randombugs]$ mvn install

Now we should have all jar files in Apache Maven repository which in my case is /usr/local/apache-maven-2.2.1/log4j/

3. Testing Log4J
To test build it jar’s I need a simple program to do that. I found a simple and clear piece of code here: http://www.devdaily.com/blog/post/java/simple-log4j-example and I adapted for my needs:

Log4JDemo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package testlog4j;
 
import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
 
public class Log4JDemo
{
  static final Category log = Category.getInstance(Log4JDemo.class);
  static final String LOG_PROPERTIES_FILE = "testlog4j/Log4J.properties";
 
  public static void main(String[] args)
  {
    // call our constructor
    new Log4JDemo();
    // Log4J is now loaded; try it
    log.info("leaving the main method of Log4JDemo");
  }
 
  public Log4JDemo()
  {
    initializeLogger();
    log.info( "Log4JDemo - leaving the constructor ..." );
  }
 
  private void initializeLogger()
  {
    Properties logProperties = new Properties();
 
    try
    {
      logProperties.load(new FileInputStream(LOG_PROPERTIES_FILE));
      PropertyConfigurator.configure(logProperties);
      log.info("Logging initialized.");
    }
    catch(IOException e)
    {
      throw new RuntimeException("Unable to load logging property " + LOG_PROPERTIES_FILE);
    }
  }
}

Create a folder named testlog4j under /usr/src and add Log4JDemo.java there.
Now we need to compile our source and execute it:

[rb@randombugs]$ cd /usr/src
[rb@randombugs]$ javac -classpath testlog4j/log4j-1.2.16-SNAPSHOT.jar testlog4j/Log4JDemo.java

Now create a file Log4J.properties in the testlog4j folder with the following content:

Log4J.properties

1
2
3
4
5
6
7
8
9
10
11
log4j.appender.DB=org.apache.log4j.db.DBAppender
log4j.appender.locationInfo=true
log4j.appender.DB.connectionSource=org.apache.log4j.db.DriverManagerConnectionSource
log4j.appender.DB.connectionSource.driverClass=com.mysql.jdbc.Driver
log4j.appender.DB.connectionSource.url=jdbc:mysql://localhost:3306/log4j
log4j.appender.DB.connectionSource.user=log4j
log4j.appender.DB.connectionSource.password=log4jpassword
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
log4j.appender.DB.layout.ConversionPattern=%d %-5p [%t] %c - %m%n
 
log4j.category.testlog4j.Log4JDemo=INFO, DB

To test our configuration we should create log4j database and set the correct rights for log4j.

$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1307
Server version: 5.1.37-2-log (Debian)

Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the current input statement.

mysql> create database log4j;
Query OK, 1 row affected (0.00 sec)

mysql> grant all on log4j.* to log4j@localhost identified by ‘log4jpassword’;
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> ^DBye

Now we need to upload the database structure:

[rb@randombugs]$ mysql -u root -p log4j < /usr/src/apache-log4j-receivers/src/main/java/org/apache/log4j/db/dialect/mysql.sql

Now it should be ready to run a test:

[rb@randombugs]$ java -classpath testlog4j/log4j-1.2.16-SNAPSHOT.jar:testlog4j/apache-log4j-receivers-1.0.jar:testlog4j/apache-log4j-component-1.0-SNAPSHOT.jar:testlog4j/mysql.jar:. testlog4j.Log4JDemo

It should not return anything on STDOUT, but in log4j database we should see the logs:

[rb@randombugs]$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1314
Server version: 5.1.37-2-log (Debian)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use log4j;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-------------------------+
| Tables_in_log4j         |
+-------------------------+
| logging_event           |
| logging_event_exception |
| logging_event_property  |
+-------------------------+
3 rows in set (0.00 sec)

mysql> select * from logging_event;
+-----------------+---------------+-----------------------------------------+---------------------+--------------+------+-------------+----------------+-----------------+--------------+---------------+-------------+----------+
| sequence_number | timestamp     | rendered_message                        | logger_name         | level_string | ndc  | thread_name | reference_flag | caller_filename | caller_class | caller_method | caller_line | event_id |
+-----------------+---------------+-----------------------------------------+---------------------+--------------+------+-------------+----------------+-----------------+--------------+---------------+-------------+----------+
|               0 | 1253808265467 | Logging initialized.                    | testlog4j.Log4JDemo | INFO         | NULL | main        |              0 | ?               | ?            | ?             | ?           |        1 |
|               0 | 1253808265517 | Log4JDemo - leaving the constructor ... | testlog4j.Log4JDemo | INFO         | NULL | main        |              0 | ?               | ?            | ?             | ?           |        2 |
|               0 | 1253808265540 | leaving the main method of Log4JDemo    | testlog4j.Log4JDemo | INFO         | NULL | main        |              0 | ?               | ?            | ?             | ?           |        3 |
|               0 | 1253822673336 | Logging initialized.                    | testlog4j.Log4JDemo | INFO         | NULL | main        |              0 | ?               | ?            | ?             | ?           |        4 |
|               0 | 1253822673378 | Log4JDemo - leaving the constructor ... | testlog4j.Log4JDemo | INFO         | NULL | main        |              0 | ?               | ?            | ?             | ?           |        5 |
|               0 | 1253822673400 | leaving the main method of Log4JDemo    | testlog4j.Log4JDemo | INFO         | NULL | main        |              0 | ?               | ?            | ?             | ?           |        6 |
+-----------------+---------------+-----------------------------------------+---------------------+--------------+------+-------------+----------------+-----------------+--------------+---------------+-------------+----------+
6 rows in set (0.00 sec)

Good Luck!


7 Comments »

  • Changing Logging system in Glassfish 2.1 | Random Bugs said:

    […] If you don’t have maven (mvn) installed just look on my old tutorial about log4j and dbappender […]

  • Henrik said:

    I see that JDBCAppender will not log stacktraces (http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/jdbc/JDBCAppender.html). Will dbappender do this?

  • admin (author) said:

    Yes and even more. DBAppender have support for JNDI. Just Give it a try.

    Regards

  • Bruce said:

    I see that JDBCAppender will not log stacktraces (http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/jdbc/JDBCAppender.html). Will dbappender do this?

  • lake travis boat rental said:

    My Function is working when its is properly coded like above.But it is not working with custom exception handler.It shows error directly to the page and but the custom error message does not shown.

  • wastewater treatment said:

    Thanks for giving the bug tracking code.It help me so much, that I can easily use it my application.This is versatile and bug fixed.

  • component receivers reviews said:

    First off I would like to say great blog! I had a quick question which I’d like to ask if you do not mind. I was curious to find out how you center yourself and clear your mind before writing. I’ve
    had a difficult time clearing my thoughts in getting my thoughts out.
    I truly do enjoy writing but it just seems like the first 10 to 15 minutes are lost simply just trying to figure out how to begin.
    Any suggestions or tips? Appreciate it!

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.