logger and FileHandler in java

imalak picture imalak · May 4, 2012 · Viewed 11.2k times · Source

I want to print date and time in file not in the Screen

this is my code:

String fileName =  NameEnter.getText(); 
Logger logger = Logger.getLogger("puzzleNumberGame.securityScreen");  
FileHandler fh = new FileHandler(fileName);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.log(Level.WARNING,"My first log");

I use this

// handlers = java.util.logging.ConsoleHandler;

but it is not working Thanks for all :)

Answer

Apurv picture Apurv · May 4, 2012

Include a static definition in the class as follows

private final static Logger LOGGER = Logger.getLogger("nescent");

Then setupLogger as follows.

    private static void setupLogger(){
    LOGGER.setLevel(Level.ALL);
    try {
            FileHandler fhandler = new FileHandler("Logfile.txt");
            SimpleFormatter sformatter = new SimpleFormatter();
            fhandler.setFormatter(sformatter);
            LOGGER.addHandler(fhandler);

    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (SecurityException ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
    }
}