imalak
imalak

Reputation: 11

logger and FileHandler in java

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 :)

Upvotes: 1

Views: 14758

Answers (2)

Saimir_H
Saimir_H

Reputation: 1

Here is my take on this: In the try{} block provide the instantiation for FileHandler and SimpleFormatter objects. To log data in the file the methods of the Logger class must be out of the try block. Here is the code:

public static void setupLogger(){

    LOGGER.setLevel(Level.ALL);
    LOGGER.info("doing stuff");


    try{

        FileHandler fhandler = new FileHandler("Logfile.txt");
        SimpleFormatter sformatter = new SimpleFormatter();
        fhandler.setFormatter(sformatter);
        //This message does not log in the Logfile.txt, rather it logs in the console
        LOGGER.log(Level.WARNING, "first log");
        LOGGER.fine("information");
        LOGGER.addHandler(fhandler);

    }catch(  IOException | SecurityException e){
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
    LOGGER.log(Level.WARNING, "Warning message");
    LOGGER.fine("This message is logged in the file");
}

Upvotes: 0

Apurv
Apurv

Reputation: 4525

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);
    }
}

Upvotes: 2

Related Questions