Search code examples
javaloggingfilehandler

Java: check if logger is empty so it does not creat a txt file


I have a class named Logg. That i use for send every exception or other warnings. before it creates a file, I want to check if it has anything to write to the file. So it does not create a empty txt file.

code:

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


    }
}

}


Solution

  • You can solve this issue by installing a proxy handler on the root logger to lazily run your logging config. The proxy handler level must be the same level as your FileHandler. Your FileHandler will only get created if something is published to the proxy handler. Here is some example code:

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

    You have to modify your startup code to manually install this on the root logger or you have to create a logging.properties file to install this handler. As in:

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