Java:检查logger是否为空,这样就不会创建txt文件

时间:2015-02-12 08:52:29

标签: java logging filehandler

我有一个名为Logg的类。我用它来发送每个异常或其他警告。 在创建文件之前,我想检查它是否有任何要写入文件的内容。所以它不会创建一个空的txt文件。

代码:

 package ast;
 /**
 *Handles logging
 * Configured from the config.property file at resources
 */

public class Logg {
private final static Logger logger = Logger.getLogger(Logg.class.getName());
private static FileHandler fh = null;

/**
 * Checks parameter Savemethod gets from config file
 * and what logging Level you have chosen
 *
 * @param saveMethod
 * @param Logg       Level
 * @throws IOException
 * @throws Exception
 */
public static void init() throws IOException {

    Properties prop = new Properties();
    InputStream in = Logg.class.getResourceAsStream("loggconfig");
    if (in != null) {
        prop.load(in);
    } else {
        throw new FileNotFoundException("property file '" + in + "' not found in the classpath");
    }

    int saveMethod = Integer.parseInt(prop.getProperty("Savemethod"));

    if(saveMethod == 1){

        ConsoleHandler handler = new ConsoleHandler();
        handler.setLevel(Level.ALL);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);

    }
    //Creates and Names the logg file to current date
    else if (saveMethod == 2) {
        try {
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
            fh = new FileHandler((dateFormat.format(date) + ".log"), false);
            Logger l = Logger.getLogger("");
            fh.setFormatter(new SimpleFormatter());
            l.addHandler(fh);

            l.setLevel(Level.parse(prop.getProperty("Level")));


        } catch (Exception e) {
            logger.log(Level.INFO, "Error in Logg", e);
        }


    }
}

}

1 个答案:

答案 0 :(得分:0)

您可以通过在根记录器上安装代理处理程序来懒惰地运行日志记录配置来解决此问题。代理处理程序级别必须与FileHandler的级别相同。只有在向代理处理程序发布内容时才会创建FileHandler。以下是一些示例代码:

     public class ConfigHandler extends Handler {

        private FileHandler fh;
        private ConsoleHandler ch;

        public ConfigHandler() {
            String p = getClass().getName();
            LogManager m = LogManager.getLogManager();
            try {
                String s = m.getProperty(p + ".level");
                if (s != null) {
                    super.setLevel(Level.parse(s));
                }                
            } catch (RuntimeException re) {
                super.reportError("", re, ErrorManager.OPEN_FAILURE);
            }
        }

        @Override
        public synchronized void publish(LogRecord record) {
            try {
                init(record);
            } catch (RuntimeException re) {
                reportError(null, re, ErrorManager.WRITE_FAILURE);
            } catch (Exception e) {
                reportError(null, e, ErrorManager.WRITE_FAILURE);
            }

            Handler h = this.ch;
            if (h != null) {
                h.publish(record);
            }

            h = this.fh;
            if (h != null) {
                h.publish(record);
            }
        }

        @Override
        public synchronized void flush() {
            Handler h = this.ch;
            if (h != null) {
                h.flush();
            }

            h = this.fh;
            if (h != null) {
                h.flush();
            }
        }

        @Override
        public synchronized void close() throws SecurityException {
            super.setLevel(Level.OFF);
            Handler h = this.ch;
            if (h != null) {
                h.close();
            }

            h = this.fh;
            if (h != null) {
                h.close();
            }
        }

        private boolean allowConsole(LogRecord r) {
            return isLoggable(r);
        }

        private boolean allowFile(LogRecord r) {
            return isLoggable(r);
        }

        private void init(LogRecord r) throws IOException {
            assert Thread.holdsLock(this) : this;
            if (ch != null && fh != null) {
                return;
            }

            Properties prop = new Properties();
            InputStream in = ConfigHandler.class.getResourceAsStream("loggconfig");
            if (in != null) {
                prop.load(in);
            } else {
                throw new FileNotFoundException("property file '" + in + "' not found in the classpath");
            }

            int saveMethod = Integer.parseInt(prop.getProperty("Savemethod"));

            if (saveMethod == 1) {
                if (ch == null && allowConsole(r)) {
                    ch = new ConsoleHandler();
                    ch.setLevel(Level.ALL);
                    ch.setFormatter(new SimpleFormatter());
                }
            } //Creates and Names the logg file to current date
            else if (saveMethod == 2) {
                try {
                    if (fh == null && allowFile(r)) {
                        Date date = new Date();
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
                        fh = new FileHandler((dateFormat.format(date) + ".log"), false);
                        fh.setFormatter(new SimpleFormatter());
                    }
                    Logger l = Logger.getLogger(""); //???
                    l.setLevel(Level.parse(prop.getProperty("Level")));

                } catch (Exception e) {
                    reportError(null, e, ErrorManager.WRITE_FAILURE);
                }
            }
        }
    }

您必须修改启动代码才能在根记录器上手动安装它,或者您必须创建logging.properties文件来安装此处理程序。如:

public static void main(String[] args) {
    Logger.getLogger("").addHandler(new ConfigHandler());
}