logger例子 能自己指定log文件的存放位置

闲来无聊  遂研究研究日志输出

开始发现不能指定到我想要的目录

后面终于解决了   现在分享给大家

 

import java.io.File;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.logging.FileHandler;

import java.util.logging.Level;

import java.util.logging.Logger;

import java.util.logging.SimpleFormatter;

 

public class LoggerUtil {

 

    /** 存放的文件夹 **/

    private static String file_name = "系统日志";

 

    /**

     * 得到要记录的日志的路径及文件名称

     * @return

     */

    private static String getLogName() {

        StringBuffer logPath = new StringBuffer();

        System.setProperty("log", "d://");// 这里设置一个自定义的key作为存日志的目录

        logPath.append(System.getProperty("log")); // 现将自定义的目录取出来

        logPath.append("//"+file_name);

        File file = new File(logPath.toString());

        if (!file.exists())

            file.mkdir();

 

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        logPath.append("//"+sdf.format(new Date())+".log");

 

        return logPath.toString();

    }

 

    /**

     * 配置Logger对象输出日志文件路径

     * @param logger

     * @throws SecurityException

     * @throws IOException

     */

    public static void setLogingProperties(Logger logger) throws SecurityException, IOException {

        setLogingProperties(logger,Level.ALL);

    }

 

    /**

     * 配置Logger对象输出日志文件路径

     * @param logger

     * @param level 在日志文件中输出level级别以上的信息

     * @throws SecurityException

     * @throws IOException

     */

    public static void setLogingProperties(Logger logger,Level level) {

        FileHandler fh;

        try {

            fh = new FileHandler(getLogName(),true);

            logger.addHandler(fh);//日志输出文件

            //logger.setLevel(level);

            fh.setFormatter(new SimpleFormatter());//输出格式

            //logger.addHandler(new ConsoleHandler());//输出到控制台

        } catch (SecurityException e) {

            logger.log(Level.SEVERE, "安全性错误", e);

        } catch (IOException e) {

            logger.log(Level.SEVERE,"读取文件日志错误", e);

        }

    }

 

    public static void main(String [] args) {

        Logger logger = Logger.getLogger("sgg");

        try {

            LoggerUtil.setLogingProperties(logger);

            logger.log(Level.INFO, "http://2x-cnc.7moo.com ");

            logger.log(Level.INFO, "云夕 ");

            logger.log(Level.INFO, "http://www.baidu.com");

            logger.log(Level.INFO, "百度 ");

            logger.log(Level.INFO, "http://www.google.com.hk");

 

            logger.log(Level.INFO, "谷歌 ");

        } catch (SecurityException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

 

 

 

    }

}

上面仅仅是个例子  在实际应用中还要优化下

你可能感兴趣的:(logger例子 能自己指定log文件的存放位置)