2

This is my log4j properties file. I'm writing logs into db. I want to set the db credentials at run time

log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DB.URL=jdbc:sqlserver://172.16.0.201:1433;databaseName=databaseone;autoReconnect=true
log4j.appender.DB.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
log4j.appender.DB.user=username
log4j.appender.DB.password=password$123
log4j.appender.DB.sql=INSERT INTO usage_fact(accessed_date,accessed_item_id,user_id,tenant_id,log_level) VALUES('%d{yyyy-MM-dd HH:mm:ss}','%X{accessed_item_id}','%X{user_id}','%X{tenant_id}','%p')
log4j.appender.DB.layout=org.apache.log4j.PatternLayout

And how do i catch the sql exception arises while log4j connecting to db or writing into table. all exception stack trace are printing on console i don't want to print this on console.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Prasad V S
  • 262
  • 4
  • 17

1 Answers1

4

You can initialize the logging framework through java code like this:

public class CoreLogger {
    public static Logger getLogger(final Class moduleName) {
        Logger logger = Logger.getLogger(moduleName);
        Properties prop = new Properties();
        try {
            prop.load(new FileReader("log4j.properties"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        prop.put("log4j.appender.DB.user", "root");
        prop.put("log4j.appender.DB.password", "root");
        PropertyConfigurator.configure(prop);
        return logger;
    }
}

and use

static Logger log = CoreLogger.getLogger(Demo.class);

In your classes to get the instance of logger, this way you can set the credentials at run time.

Regarding capturing errors in files, you can redirect stdout and stderr to your log files refer Dario's answer at log4j redirect stdout to DailyRollingFileAppender for more details about that.

Community
  • 1
  • 1
Manish Kothari
  • 1,702
  • 1
  • 24
  • 34
  • Run time properties changing is working fine, But before that log4j trying to connect to data base its printing sql exception on my tomcat console. how to make log4j internal logs not to print on console – Prasad V S Apr 19 '16 at 06:41
  • For that you can refer the link I have provided in the answer. – Manish Kothari Apr 19 '16 at 08:42