我有一个通过静态 block 实例化模式的 bean,以便为 MyClass 的每个实例加载一次。但是我从未看到日志记录(当我输入错误的文件路径时只看到一次,所以这是异常的日志记录)。如果我用 System.out.println() 替换日志记录,它会显示在控制台中。
我的项目使用SLF4J和LOG4J。我见过这个问题:Putting Logger.info in static block它声称 LOG4J 应该在执行静态 block 时初始化。我的预感是,使用 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;
}
}
最佳答案
只需省略此 if 语句即可
if (XSD_SCHEMA != null) {
事实上,它始终为 false,并且静态 block 永远不会执行任何有用的内容。
您不需要它,因为静态 block 无论如何都只会执行一次。
关于java - 我的日志记录去哪里了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25077237/