Java Logg处理异常类
我有两个类GetStatus和Logg GetStatus从一个xml文件中读取并选取两个元素,然后检查值是否正确。我们在GetStatus中尝试并捕获了一些异常Java Logg处理异常类,java,logging,Java,Logging,我有两个类GetStatus和Logg GetStatus从一个xml文件中读取并选取两个元素,然后检查值是否正确。我们在GetStatus中尝试并捕获了一些异常 } catch (IOException ex) { logger.log(Level.WARNING, "wrong or interrupted I/O operations.",ex); }catch (NumberFormatException ex) { logger.log(Le
} catch (IOException ex) {
logger.log(Level.WARNING, "wrong or interrupted I/O operations.",ex);
}catch (NumberFormatException ex) {
logger.log(Level.WARNING, "Wrong argument format", ex);
} catch (ParserConfigurationException ex) {
logger.log(Level.WARNING, "Indicates a serious configurationerror",ex);
} catch (SAXException ex) {
logger.log(Level.WARNING, "XML Parsing error", ex);
我们希望将异常发送到另一个类,并创建一个文件并记录异常。但我们希望选择是否必须记录异常,或者只是打印到终端或控制台。我们希望通过java.util.logging实现这一点
这是我们的日志类
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM-dd_HH-mm-ss");
if (saveMethod == 1) {
try {
fh = new FileHandler((dateFormat.format(date) + ".log"), false);
} catch (Exception e) {
logger.log(Level.WARNING, "Wrong in Logg", e);
Logger l = Logger.getLogger("");
fh.setFormatter(new SimpleFormatter());
l.addHandler(fh);
l.setLevel(Level.INFO);
}
}
else{
System.err.println("You have not chosen save method!");
}
return 0;
此时,它每次都创建一个文件。它可能每次都创建一个新文件,因为您每次都给它一个不同的文件名(因为它基于当前时间) 有什么原因不能有一个静态的“记录器”字段,例如
public class MyClass {
public static final Logger LOGGER = Logger.getLogger(MyClass.class);
...
}
我假设您使用的是log4j1.2?如果是这样,您可以将其配置为使用文件追加器,该追加器将每天创建一个新的日志文件。请参阅此链接
刚刚解决了我的问题!使用类属性,并从名为config的属性文件中获取level参数,这样我就可以选择要登录到文件中的级别,或者在终端或控制台中打印出来 该类将从另一个类获取参数
public class Logg {
private final static Logger logger = Logger.getLogger(Logg.class.getName());
private static FileHandler fh = null;
public static void init(int saveMethod) throws IOException {
String level= "";
Properties prop = new Properties();
InputStream in =
Logg.class.getResourceAsStream("resources\\config");
if (in != null) {
prop.load(in);
} else {
throw new FileNotFoundException("property file '" + in + "' not found in the classpath");
}
level = prop.getProperty("Level");
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH-mm");
if (saveMethod == 1) {
try {
fh = new FileHandler((dateFormat.format(date) + ".log"), false);
} catch (Exception e) {
logger.log(Level.INFO, "problems in logg class", e);
}
Logger l = Logger.getLogger("");
fh.setFormatter(new SimpleFormatter());
l.addHandler(fh);
l.setLevel(Level.parse(level));
System.out.println(level);
} else {
System.err.println("You have not chosen save method!");
}
}
}每次运行程序时,我们都需要一个新文件。我认为我们正在使用java.util.logging。