【问题标题】:Where does my logging go?我的日志记录在哪里?
【发布时间】: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

标签: java logging log4j slf4j


【解决方案1】:

只需省略这个 if 语句

if (XSD_SCHEMA != null) {

事实上,它总是假的,静态块永远不会执行任何有用的东西。

你不需要它,因为静态块无论如何只会被执行一次。

【讨论】:

    猜你喜欢
    • 2019-01-22
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    相关资源
    最近更新 更多