java中的logger和FileHandler

时间:2012-05-04 04:18:44

标签: java logging filehandler

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

这是我的代码:

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;

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

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

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

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