Reputation: 551
The problem is that Logger is not initialized using Logger.getLogger(class_name.class.getName())
approach.
You can see the codes below. I marked the line which leads to the exception.
I must note that I tried without static setLevel
block as well.
// 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();
}
}
Could you please tell me what exactly leads to this error?
Upvotes: 0
Views: 7983
Reputation: 7326
Because you have never defined a Logger with the name "Experience". When you call getLogger(String) it looks for a defined logger with that name. Try just doing Logger.getLogger(Experience.class), that should get you the logger for Experience
Upvotes: 0
Reputation: 1504172
The trouble is that these two static variable initializers are executed in textual order:
private final static Experience INSTANCE = new Experience();
public final static Logger LOGGER = Logger.getLogger(Experience.class.getName());
So when the first line calls the constructor, which includes this:
LOGGER.addHandler(fh);
... LOGGER
is still null.
The simplest fix would be to just reverse the order of the declarations... but another, clearer alternative would be to do it all in the static initializer:
private final static Experience INSTANCE;
public final static Logger LOGGER;
static {
LOGGER = Logger.getLogger(Experience.class.getName());
LOGGER.setLevel(Level.SEVERE);
INSTANCE = new Experience();
}
(Out of interest, do you really want the logger to be public?)
Upvotes: 8