关闭log4j记录器以释放文件描述符[英] Closing log4j Logger to release File Descriptor

本文是小编为大家收集整理的关于关闭log4j记录器以释放文件描述符的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我写了一台接收RMI请求并执行一些操作的服务器.

对于每个请求,创建了log4j logger实例.以下是用于创建Logger实例的代码段.

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);

在这里工作正常.问题是在收到大量请求后加班,此服务器过程的开放文件数量增加,并且不会降低,从而使该过程崩溃了,但有一个例外,说 太多的打开文件.

进一步检查后,发现问题是因为在请求完成后未发布文件描述符.我已经尝试查看Log4J文档,但找不到有关如何仅关闭一个记录器而不会影响其他可能在不同线程中运行的任何内容的任何内容.

这里有什么想法?

推荐答案

看一下apache.org/log4j/1.2/apidocs/org/apache/log4j/writerappender.html#close; .close()文档,也许它将解决您的问题.

,但我认为您应该重新考虑您的设计,并且只有一个记录器实例,没有?

其他推荐答案

使您的记录器最终静态应解决问题:

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

本文地址:https://www.itbaoku.cn/post/1575021.html

问题描述

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?

推荐答案

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 ?

其他推荐答案

Make your logger final static should fix the problem:

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