1

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

Yurets
  • 3,999
  • 17
  • 54
  • 74
imalak
  • 11
  • 1
  • 1
  • 3
  • 1
    What is not working? What results are you seeing? Are you getting an error message? – awmross May 04 '12 at 04:21
  • I think you are better well off getting a logging library like [log4j](http://logging.apache.org/log4j/1.2/manual.html) before you do it yourself from scratch. – Jasonw May 04 '12 at 04:44

2 Answers2

2

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);
    }
}
Apurv
  • 4,458
  • 2
  • 21
  • 31
0

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");
}
Saimir_H
  • 1
  • 1