I am trying to create a new logger for my plugin. However it does not write any content to the file. The logging events provide no errors. If I do not supply a handler I can get all the log events in the console.
It seems the logger is handling the file, as it creates a chatlog.log.lck
file.
Subsequently, is there a way to also log what is logged to my "new" logger, to the console as well?
private void setupLogger() {
logger = Logger.getLogger("WeChat");
File lf = new File(getDataFolder() + File.separator + "logs");
if (!(lf.exists())){
lf.mkdirs();
}
try {
FileHandler fh = new FileHandler(getDataFolder() + File.separator + "logs" + File.separator + "chatlog.log", true);
SimpleFormatter fmt = new SimpleFormatter();
fh.setFormatter(fmt);
logger.addHandler(fh);
logger.setLevel(Level.INFO);
} catch (SecurityException | IOException e) {
e.printStackTrace();
}
}
Again I can get input in the console, just no the file
[23:48:24 INFO]: [WeChat] [Channel TheLounge] WASasquatch: Hello everyone!?
[23:48:30 INFO]: [WeChat] [Channel TheLounge] WASasquatch: Test test
[23:48:36 INFO]: [WeChat] [Channel TheLounge] WASasquatch: This in the log file now?
There is a constructor in FileHandler
to set the file as append or not. (and to set a rolling file system if needed, same constructor without the rolling system exist).
public FileHandler(String pattern,
int limit,
int count,
boolean append)
throws IOException,
SecurityException
Defined the level for this handler if needed, defaults to Level.ALL
Here is a quick sample :
public class Main {
static Logger logger;
public static void main(String[] args) {
logger = Logger.getLogger("Main");
FileHandler fh;
File lf = new File("data" + File.separator + "logs" + File.separator + "chatlog.log");
if (!(lf.getParentFile().exists())){
lf.getParentFile().mkdirs();
}
try {
fh = new FileHandler(lf.getCanonicalPath(), 8096, 1, true);
logger.addHandler(fh);
logger.setLevel(Level.INFO);
SimpleFormatter fmt = new SimpleFormatter();
fh.setFormatter(fmt);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("foo");
logger.info("bar");
}
}
Note the update to use the File
instance path instead of recreate the String.
I use an none existant folder. Launch the process twice and as expected, the file as the line for both execution.