Creating a new Logger

I am trying to create a new log for my plugin. However, it doesn't write any content to the file. Registration events are error free. If I don't put in a handler, I can get all the log events in the console.

The registrar seems to be processing the file as it creates the file chatlog.log.lck

.

Subsequently, is there a way to also log what is being written to my "new" registrar to the console?

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 the console input, just no 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?

      

+3


source to share


1 answer


There is a constructor in FileHandler

to set the file as added or not. (and install a sliding file system if necessary, the same constructor without a rolling system).

public FileHandler(String pattern,
       int limit,
       int count,
       boolean append)
        throws IOException,
               SecurityException

      

A specific level for this handler, if needed defaults to Level.ALL

Here's an example:



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 instance path File

instead of recreating the string.

I am using a non existing folder. Run the process twice and, as expected, file as string for both executions.

0


source







All Articles