Programmatic configuration of logger/appender

162 Views Asked by At

How to write below configuration using Java code?

log4j.com.saurabh.util.LogUtil=DEBUG, myAppender

I am working on legacy code which is using log4j 1.x, I don't have choice to upgrade log4j version.

Basically, my requirement is to have session level logging. For each user session separate log file should be created.

    RollingFileAppender userSessionAppender = null;
    try {
        String logFile = new StringBuffer(CATALINA_HOME)
                            .append(File.separator)
                            .append(LOG_DIR)
                            .append(File.separator)
                            .append(InetAddress.getLocalHost().getHostName())
                            .append("_")
                            .append(userName)
                            .append("_")
                            .append((new SimpleDateFormat("yyyy-MM-dd.hh-mm-ss")).format(new Date()).toString())
                            .append(LOG_FILE_EXTN)
                            .toString();

        userSessionAppender = new RollingFileAppender(new PatternLayout(pattern), logFile);
        userSessionAppender.setName(sessionId);
        userSessionAppender.setThreshold(Level.DEBUG);
        // add a filter so we can ignore any logs from other user sessions
        userSessionAppender.addFilter(new SessionIdFilter(sessionId));
        rootLogger.addAppender(userSessionAppender);
        Logger.getLogger(sessionId).addAppender(userSessionAppender);
        Logger.getLogger(sessionId).setLevel(Level.DEBUG);
        Logger.getLogger(sessionId).setAdditivity(false);
    } catch (Exception e) {
        LOG.error("createLogger() : Exception while creating appender for user: " + userName, e);
    }

and to actually log the message:

if (isLoggingEnabled(userName)) {
            Logger.getLogger(sessionId).debug(message);
        }

Using this code, I am able to create separate file and log into that however, log statements from other classes are also going into the same file.

I want to restrict the logging to this file for specific classes/packages. And I think below line of config helps for this:

log4j.com.saurabh.util.LogUtil=DEBUG, myAppender

I need programmatic way to achieve above line of config.

Thanks in advance.

0

There are 0 best solutions below