【发布时间】:2014-08-01 09:39:27
【问题描述】:
我有一个通过静态块实例化模式的 bean,以便为 MyClass 的每个实例加载一次。但是我从来没有看到日志记录(当我输入错误的文件路径时只看到一次,所以这是异常的日志记录)。如果我用System.out.println() 替换日志记录,它会显示在控制台中。
我的项目使用 SLF4J 和 LOG4J。我见过这个问题:Putting Logger.info in static block,它声称 LOG4J 应该在静态块执行时已经初始化。我的预感是,通过使用 SLF4J,这不再得到保证。对吗?
private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);
private static Schema XSD_SCHEMA = null;
static {
// NB The logging in this static block does not always appear in the output. It seems
// that the indirection between SLF4J and LOG4J causes slow initialization of the logging
// framework.
if (XSD_SCHEMA != null) {
LOGGER.info("Reading schema...");
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = null;
try {
schema = sf.newSchema(new File("some.xsd"));
LOGGER.info("Read schema successfully, using validation...");
} catch (SAXException e) {
LOGGER.error("Could not load validation schema, not using validation (Reason {})",
e);
}
XSD_SCHEMA = schema;
}
}
【问题讨论】:
-
如果
LOGGER没有被初始化,你会得到一个NullPointerException。