Monday, November 14, 2011

Programmatically enabling log4j appenders

The standard way to enable 'appenders' in log4j is using log4j.properties file..Here lets check out how an user can enable the 'appenders' programmaticly..This is useful , when user wants a logging mechanism separately, which differs from his/her global logging setting..
This is a sample code i have written to grab proxy service level logging information separately..

    private void setLogger(ProxyService proxy) throws IOException {

        String filename = "logs/" + proxy.getName() + ".log";
        String datePattern = "yyyy-MM-dd";
        String SYSTEM_LOG_PATTERN = "[%d] %5p - %x %m {%c}%n";

        PatternLayout layout = new PatternLayout(SYSTEM_LOG_PATTERN);

        DailyRollingFileAppender appender = null;

        appender = new DailyRollingFileAppender(layout, filename, datePattern);

        Logger proxyLogger = Logger.getLogger("SERVICE_LOGGER." + proxy.getName());

        proxyLogger.setLevel((Level) Level.DEBUG);

        proxyLogger.setAdditivity(false);
        proxyLogger.addAppender(appender);

    }   

No comments:

Post a Comment