0

问题是 Logger 没有使用 Logger.getLogger(class_name.class.getName())方法初始化。你可以看到下面的代码。我标记了导致异常的行。我必须注意,我也尝试过不使用静态setLevel块。

// File that contains logger
public class Experience {

private final static Experience INSTANCE = new Experience(); 
private final static Logger LOGGER = Logger.getLogger(Experience.class.getName());

private MainFrame main_frame;

static {
    LOGGER.setLevel(Level.SEVERE);
    }

public static Experience getInstance()
    {
    return INSTANCE;
    }

private Experience()
    {
    try
        {
        FileHandler fh = new FileHandler(System.getProperty("user.dir") + "/log.txt");
        fh.setFormatter(new XPLogFormatter());
        LOGGER.addHandler(fh); // NULLPOINTEREXCEPION HERE
        }
    catch (Exception e)
        {
        e.printStackTrace();
        }
    }
}


// Just a loader
public class Loader
{
public static void main(String args[])
    {
    JFrame.setDefaultLookAndFeelDecorated(true);

    SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
                {
                MainFrame main_frame = new MainFrame();
                }
        });
    }
}


// Stripped down version of main frame
public class MainFrame extends JFrame
{
private Experience XP;

public MainFrame()
    {
    super();
    XP = Experience.getInstance(this);
    }
}


// Modified formatter
public class XPLogFormatter extends Formatter
{
@Override
public String format(LogRecord record)
    {
    StringBuffer buf = new StringBuffer(1000);
    buf.append(formatMessage(record));
    return buf.toString();
    }
}

你能告诉我究竟是什么导致了这个错误吗?

4

2 回答 2

8

问题是这两个静态变量初始化器是按文本顺序执行的:

private final static Experience INSTANCE = new Experience(); 
public final static Logger LOGGER = Logger.getLogger(Experience.class.getName());

因此,当第一行调用构造函数时,其中包括:

LOGGER.addHandler(fh);

...LOGGER仍然为空。

简单的解决方法是颠倒声明的顺序......但另一个更清晰的选择是在静态初始化程序中完成所有操作:

private final static Experience INSTANCE;
public final static Logger LOGGER;

static {
    LOGGER = Logger.getLogger(Experience.class.getName());
    LOGGER.setLevel(Level.SEVERE);
    INSTANCE = new Experience();
}

(出于兴趣,您真的希望记录器公开吗?)

于 2012-08-31T21:05:04.873 回答
0

因为您从未定义过名为“Experience”的 Logger。当您调用 getLogger(String) 时,它会查找具有该名称的已定义记录器。尝试只做 Logger.getLogger(Experience.class),这应该会让你成为 Experience 的记录器

于 2012-08-31T21:05:13.843 回答