我正在使用配置了log4j.xml的log4j(通过slf4j)。我想知道如何禁用log4j显示的消息。 例如,如果无法创建log4j.xml中指定的日志文件,则log4j会在控制台上显示以下消息:
log4j:ERROR setFile(null,true) call failed. java.io.FileNotFoundException: \LogFile.log (Accesso negato) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:212) at java.io.FileOutputStream.<init>(FileOutputStream.java:136) at org.apache.log4j.FileAppender.setFile(FileAppender.java:294) at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:207) at org.apache.log4j.FileAppender.activateOptions(FileAppender.java:165) at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:307) at org.apache.log4j.xml.DOMConfigurator.parseAppender(DOMConfigurator.java:295) at org.apache.log4j.xml.DOMConfigurator.findAppenderByName(DOMConfigurator.java:176) at org.apache.log4j.xml.DOMConfigurator.findAppenderByReference(DOMConfigurator.java:191) at org.apache.log4j.xml.DOMConfigurator.parseChildrenOfLoggerElement(DOMConfigurator.java:523) at org.apache.log4j.xml.DOMConfigurator.parseRoot(DOMConfigurator.java:492) at org.apache.log4j.xml.DOMConfigurator.parse(DOMConfigurator.java:1006) at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:872) at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:778) at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:526) at org.apache.log4j.LogManager.<clinit>(LogManager.java:127) at org.slf4j.impl.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:66) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:270) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:281)
我不希望用户看到完整的异常堆栈。 提前致谢
答案 0 :(得分:0)
解决方案是编写com.myapp.SilentErrorHandler
来实现org.apache.log4j.spi.ErrorHandler
,但不执行任何操作。
log4j.xml
中的配置为:
<appender name="file" class="org.apache.log4j.RollingFileAppender">
<errorHandler class="com.myapp.SilentErrorHandler" />
<param name="File" value="\LogFile.log"/>
<layout class="org.apache.log4j.PatternLayout">
...
</layout>
</appender>
请注意,默默地忽略错误通常是一件坏事。您可以考虑使用FallbackErrorHandler
,如果主要appender失败,则允许指定回退追加器。