java 写日志到文件

       //日志文件
        String  path = System.getProperty("user.dir");//获取项目绝对路径
        String logPath = path + "\\run.log";
        java.util.logging.Logger log = java.util.logging.Logger.getLogger(logPath);
        log.setLevel(Level.ALL);
        FileHandler fileHandler = new FileHandler(logPath,true);//true是以追加的形式
        fileHandler.setLevel(Level.ALL);
        fileHandler.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                Date date = new Date();
                String sDate = date.toString();
                return "[" + sDate + "]" + "[" + record.getLevel() + "]"
                        + record.getClass() + record.getMessage() + "\n";
            }
        });
        log.addHandler(fileHandler);
        log.info("This is test java util log1");
        log.warning("This is test java util log2");
        fileHandler.close();

适当封装下就可以啦 

注意:引入相关类

 

你可能感兴趣的:(java)