4

I have to configure the JDBC appender to use a datasource..is it possible?

if so , how? My present file looks like so:

# Define the root logger with file appender
log4j.rootLogger = DEBUG, sql

# Define the file appender
log4j.appender.sql=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.sql.URL=jdbc:mysql://localhost/test
# Set Database Driver
log4j.appender.sql.driver=com.mysql.jdbc.Driver
# Set database user name and password
log4j.appender.sql.user=root
log4j.appender.sql.password=password
# Set the SQL statement to be executed.
log4j.appender.sql.sql=INSERT INTO LOGS VALUES ('%x', now() ,'%C','%p','%m')
# Define the xml layout for file appender
log4j.appender.sql.layout=org.apache.log4j.PatternLayout
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
TimeToCodeTheRoad
  • 7,032
  • 16
  • 57
  • 70

1 Answers1

2

If you want to use a datasource, you need to add the jar file of Apache Extras for Apache log4j 1 and use the class org.apache.log4j.DBAppender 2. e.g.:

# Define the root logger with file appender
log4j.rootLogger = DEBUG, sql

# Define the database appender
log4j.appender.sql=org.apache.log4j.DBAppender
log4j.appender.sql.connectionSource=org.apache.log4j.receivers.db.JNDIConnectionSource
log4j.appender.sql.connectionSource.jndiLocation=java:/comp/env/jdbc/MySQLDS

Notes

  1. You can download the file apache-log4j-extras-1.2.17.jar here.
  2. This appender uses a database schema (not customizable) and you can find it here. If you want to use other tables, you'll need to rewrite the appender.
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
  • Hi Paul, my datasource is a bean with bean id="datasource". How do I change the above properties file to read that – TimeToCodeTheRoad Sep 04 '14 at 16:22
  • 1
    @TimeToCodeTheRoad See http://stackoverflow.com/a/11399305/870248 in order to bind your datasource to the JDNI tree. – Paul Vargas Sep 04 '14 at 16:35
  • @TimeToCodeTheRoad Or you may want to see [Programmatically Configuring log4j](http://robertmaldon.blogspot.de/2007/09/programmatically-configuring-log4j-and.html) – Paul Vargas Sep 04 '14 at 16:41
  • I have asked a similar question here. I think you can help: http://stackoverflow.com/questions/25670449/log4j-custom-jdbc-appender-datasource – TimeToCodeTheRoad Sep 05 '14 at 09:58