Salman A. Kagzi
Salman A. Kagzi

Reputation: 4053

Closing log4j Logger to release File Descriptor

I have written a Server that receives RMI requests and performs some operations.

For each request a Log4J Logger instance is created. Following is the code snippet which is used for creating Logger instance.

Logger log = Logger.getLogger("log_" + requestID);
log.setAdditivity(false);
FileAppender appender = null;
try {
    PatternLayout layout = new PatternLayout("%-5p %C{1} %d{yyyy-MM-dd HH:mm:ss} : %m%n");
    appender = new FileAppender(layout, logFileName, false);
} catch(Exception e) {
    logger.error("Error initializing logger", e);
}

log.addAppender(appender);
log.setLevel(level);

Things work fine here. The problem is overtime after receiving a lot of requests, the numbe of Open Files for this server process increases and does not come down thus crashing the process with an Exception saying Too Many Open Files.

Upon further inspection it was identified that the problem is because of the File Descriptors are not released after the the request is complete. I have tried looking through the Log4J documentation but could not find anything on how can I close just one logger without affecting the others that might be running in different threads.

Any ideas here?

Upvotes: 4

Views: 10621

Answers (2)

Jin
Jin

Reputation: 11

Make your logger final static should fix the problem:

private final static Logger logger = Logger.getLogger(YOURCLASS.class);

Upvotes: 1

ndeverge
ndeverge

Reputation: 21564

Take a look at the FileAppender.close() documentation, maybe it will solve your issue.

But I think that you should reconsider your design, and only have one Logger instance, no ?

Upvotes: 6

Related Questions