1

我想在不在屏幕上的文件中打印日期和时间

这是我的代码:

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

我用这个

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

但它不起作用谢谢大家:)

4

2 回答 2

2

在类中包含静态定义,如下所示

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

然后 setupLogger 如下。

    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);
    }
}
于 2012-05-04T04:33:27.157 回答
0

这是我对此的看法:在 try{} 块中提供 FileHandler 和 SimpleFormatter 对象的实例化。要在文件中记录数据,Logger 类的方法必须在 try 块之外。这是代码:

公共静态无效 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");
}
于 2013-10-07T16:39:44.180 回答