4
votes

How do I convert this log4j2.xml config fragment to log4j2.properties format?

I cannot use XML format in my maven + netbeans project as I simply cannot get log4j2 to parse and respond to a log4j2.xml file - no matter where I place it in my project, it is ignored by log4j2.

However log4j2.properties in main/resource IS parsed and responded to so I -HAVE- to use .properties...:

 <JDBC name="databaseAppender" tableName="LOGGING.APPLICATION_LOG">
   <ConnectionFactory class="log4j_tutorial.ConnectionFactory"
    method="getDatabaseConnection" />
   <Column name="EVENT_DATE" isEventTimestamp="true" />
   <Column name="LEVEL" pattern="%level" />
   <Column name="LOGGER" pattern="%logger" />
   <Column name="MESSAGE" pattern="%message" />
   <Column name="THROWABLE" pattern="%ex{full}" />
  </JDBC>

I'm using log4j2 2.10.0 via the official Apache Maven log4j artifacts.

What would the -correct- log4j2.properties config be to be 100% equivalent to the above?

I'm close to spending two days straight just on getting a JDBC appender working, so it is time to ask for help, methinks.

My current log4j2.properties file which works fine an outputs to file and console:

appender.file.type = File
appender.file.name = fileAppender
appender.file.fileName = verdi.log
appender.file.layout.type = PatternLayout
appender.file.layout.pattern = %d{YYYY-mm-dd HH:mm:ss.SSS} %-5p %c{1} - %m %n

appender.out.type = Console
appender.out.name = out
appender.out.layout.type = PatternLayout
appender.out.layout.pattern = %d{YYYY-mm-dd HH:mm:ss.SSS} %-5p %c{1} - %m %n

rootLogger.level = INFO
rootLogger.appenderRef.file.ref = fileAppender
rootLogger.appenderRef.out.ref = out

I literally just want to add a JDBC appender in the log4j2.properties file - the db table is already created, and I've implemented the ConnectionSource interface as per the docs, and it is backed by a connectionpooled DataSource, as per the docs. The official Apache docs however are very vague and extremely sparse with exact specifics especially as regards configuration.

I can find no official list of what elements should be in a JDBC appender when specified, and how the XML hierarchy apparent in the above must be specified in a log4j2.properties file. All examples I can find of JDBC appender configuration are -ALWAYS- log4j2.xml / XML based examples only.

Or should I give up and rather spend a few days / weeks trying to get log4j XML configuration working?

Thanks!

2

2 Answers

3
votes

I was trying to do the same thing, and am really surprised to find no examples anywhere for JDBCAppender properties configuration.

What I did discover, since I'm using PAX logging under OSGI, I can refer to an XML config file by setting org.ops4j.logging.log4j2.config.file. Having got that to work, I've now gone back and figured out the properties approach, so I think this is what you are looking for:

appender.file.type = File
appender.file.name = fileAppender
appender.file.fileName = verdi.log
appender.file.layout.type = PatternLayout
appender.file.layout.pattern = %d{YYYY-mm-dd HH:mm:ss.SSS} %-5p %c{1} - %m %n

appender.out.type = Console
appender.out.name = out
appender.out.layout.type = PatternLayout
appender.out.layout.pattern = %d{YYYY-mm-dd HH:mm:ss.SSS} %-5p %c{1} - %m %n

appender.db.type = Jdbc
appender.db.name = dbAppender
appender.db.tableName = LOGGING.APPLICATION_LOG
appender.db.cf.type = ConnectionFactory
appender.db.cf.class = log4j_tutorial.ConnectionFactory
appender.db.cf.method = getDatabaseConnection
appender.db.col1.type = Column
appender.db.col1.name = EVENT_DATE
appender.db.col1.isEventTimestamp = true
appender.db.col2.type = Column
appender.db.col2.name = LEVEL
appender.db.col2.pattern = %level
appender.db.col3.type = Column
appender.db.col3.name = LOGGER
appender.db.col3.pattern = %logger
appender.db.col4.type = Column
appender.db.col4.name = MESSAGE
appender.db.col4.pattern = %message
appender.db.col5.type = Column
appender.db.col5.name = THROWABLE
appender.db.col5.pattern = %ex{full}

rootLogger.level = INFO
rootLogger.appenderRef.file.ref = fileAppender
rootLogger.appenderRef.out.ref = out
rootLogger.appenderRef.db.ref = dbAppender

I haven't tried this exact config, since I'm using a DataSource rather than a ConnectionFactory, but I think that this should work in theory. I hope it helps.

EDIT: Add datasource definition lines as requested if datasource is required rather than connection factory:

appender.db.datasource.type = DataSource
appender.db.jndiName = osgi:service/dsName
2
votes

I was trying to do the same and got this solution. 1. Create connectionFactory.java file

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;

public class ConnectionFactory {

    private static interface Singleton {
        final ConnectionFactory INSTANCE = new ConnectionFactory();
    }
    private final DataSource dataSource;

    private ConnectionFactory() {
        Properties properties = new Properties();
        properties.setProperty("user", "aabsUser");
        properties.setProperty("password", "aj12fk18");

        GenericObjectPool pool = new GenericObjectPool();
        DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                "jdbc:mysql://localhost:3306/aabs", properties);
        new PoolableConnectionFactory(connectionFactory, pool, null,
                "SELECT 1", 3, false, false,
                Connection.TRANSACTION_READ_COMMITTED);

        this.dataSource = new PoolingDataSource(pool);
    }

    public static Connection getDatabaseConnection() throws SQLException {
        return Singleton.INSTANCE.dataSource.getConnection();
    }
}

2. make Entries in Log4j2.properties

name=PropertiesConfig
appenders=db
appender.db.type = Jdbc
appender.db.name = MySQLDatabase

# replace databaseName.tableName
appender.db.tableName =databaseName.tableName
appender.db.cf.type = ConnectionFactory

# change class path and method name
appender.db.cf.class = com.log4j2demo.ConnectionFactory
appender.db.cf.method = getDatabaseConnection
# define column type, column name and value
appender.db.col2.type = Column
appender.db.col2.name = DATE
appender.db.col2.isEventTimestamp = true

appender.db.col3.type = Column
appender.db.col3.name = LOG_LEVEL
appender.db.col3.pattern = %p

appender.db.col4.type = Column
appender.db.col4.name = FILE
appender.db.col4.pattern = %F

#Initialize logger
loggers=db
logger.db.name=com.log4j2demo.Demo
logger.db.level = All
logger.db.appenderRefs.db.ref = MySQLDatabase

#Initialize rootLogger
rootLogger.level =info
rootLogger.appenderRefs = db
rootLogger.appenderRef.db.ref = MySQLDatabase

3. Implement Logger

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Demo {

    private static Logger log = LogManager.getLogger();

    public static void main(String[] args) throws InterruptedException {
        log.trace("Entering application.");
        log.trace("Trace.");
        for (int i = 0; i < 10; i++) {
            log.info("Testing Lof For DB");
        }
        log.debug("Debug.");
        log.fatal("Fatal.");
        log.log(Level.WARN, "Warn");
        int a, b, c;
        a = 1;
        b = 0;
        try {
            c = a / b;
            log.info("vale of c" + c);
        } catch (Exception e) {
            log.error("error occur>>" + e);
        }
    }

}