我有一个名为 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);
}
}
}
}