日志框架提供了包含可配置日志记录的功能,可以在运行时和单个功能部件中启用、禁用或增加详细信息。
在lab4中使用log4j2完成基本日志功能
关于log4j2的下载
Apache官网下载Log4j2,http://logging.apache.org/log4j/2.x/download.html
向项目中导入jar包,基本上只需要导入一下两个包,xx为版本号:
log4j-core-xx.jar
log4j-api-xx.jar
在lab4中使用的版本为log4j2-2.11.2
接下来需要配置文件,与log4j1不同,2的版本中配置文件不能是properties,只能采用.xml、.json或者.jsn格式,以下相当于缺省配置文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</appenders>
<loggers>
<root level="error">
<appender-ref ref="Console"/>
</root>
</loggers>
</configuration>
关于lab4中日志的使用
在lab4中将配置文件设置为如下形式:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="File" filename="src\log.log"
filepattern="%d{YYYY-MM-dd HH:mm:ss}-fargo.log">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} %l [%t] %-5p %c{1}:%L - %msg%n" />
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>
以AtomStructure为例展示log和异常的配合使用
package CircularOrbit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import centralObject.CentralObject;
import exception.AtomNameException;
import exception.AtomTrackNumException;
import exception.AtomTrackNumMatchException;
import exception.ElectronFormatException;
import exception.ElectronNumLabelException;
import exception.StellarTrackRadiusException;
import physicalObject.PhysicalObject;
import track.Track;
public class AtomStructure<L,E> extends ConcreteCircularOrbit<L,E>{
public static Logger logger = LogManager.getLogger(AtomStructure.class.getName());
@Override
public void readFile(String filename) throws IOException,AtomNameException, AtomTrackNumException,AtomTrackNumMatchException,ElectronFormatException,ElectronNumLabelException, StellarTrackRadiusException{
String format1 = "(ElementName ::= )([A-Z][a-z]+)";
String format2 = "(NumberOfElectron ::= )(\\d+/\\d+;?)+";
String format3 = "(NumberOfTracks ::= )(\\d+)";
String pathname = "test\\txt\\"+filename;
Matcher m1,m2,m3;
String atomName = null;
int trackNum=0;
String[]trackNumber = null;
String[]tracks = null;
File file = new File(pathname);
InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
BufferedReader br = new BufferedReader(reader);
String line;
boolean f = false,ff=false,fff=false;
while((line = br.readLine())!=null) {
m1 = Pattern.compile(format1).matcher(line);
m2 = Pattern.compile(format2).matcher(line);
m3 = Pattern.compile(format3).matcher(line);
String format4 = "(NumberOfElctron ::= )([\\s\\S]*)";
Matcher m4 = Pattern.compile(format4).matcher(line);
while(m1.find()) {
atomName = m1.group(2);
char[] atomNameChar = atomName.toCharArray();
if (atomNameChar.length>2||atomNameChar.length<=0||atomNameChar==null) {
logger.error("异常类型:AtomNameException"+
"操作错误:AtomName不规范"+
"停止读取文件");
throw new AtomNameException("the name of the atom is illegal!");
}
if (atomNameChar.length==1) {
if (!Character.isUpperCase(atomNameChar[0])) {
logger.error("异常类型:AtomNameException"+
"操作错误:AtomName不规范"+
"停止读取文件");
throw new AtomNameException("the name of the atom's first character is not uppercase");
}
}
if (atomNameChar.length==2) {
if (!Character.isUpperCase(atomNameChar[0])||!Character.isLowerCase(atomNameChar[1])) {
logger.error("异常类型:AtomNameException"+
"操作错误:AtomName不规范"+
"停止读取文件");
throw new AtomNameException("the name of the atom's first character should be uppercase and the second one should be lowercase");
}
}
f = true;
CentralObject central = CentralObject.createAtom(atomName);
super.addCentralObject((L)central);
}
while(m3.find()) {
trackNum = Integer.valueOf(m3.group(2));
if (trackNum<=0) {
logger.error("异常类型:AtomTrackNumException"+
"操作错误:TrackNumber数值不规范"+
"停止读取文件");
throw new AtomTrackNumException("the number of tracks is zero!");
}
ff = true;
}
while(m2.find()) {
tracks = m2.group().split("NumberOfElectron ::= |;");
for (int i=1;i<tracks.length;i++) {
trackNumber = tracks[i].split("/");
if (trackNumber.length!=2) {
logger.error("异常类型:ElectronFormatException"+
"操作错误:电子和轨道的格式不规范"+
"停止读取文件");
throw new ElectronFormatException("the electrons on the track should use '/' to split");
}
if (trackNumber.length==2) {
Track t = new Track(Integer.valueOf(trackNumber[0]));
super.addTrack(t);
int electronNum = Integer.valueOf(trackNumber[1]);
for (int j=1;j<=electronNum;j++) {
PhysicalObject p = PhysicalObject.createElectron();
super.addPhysicalObject(t, (E)p);
}
}
}
fff = true;
}
}
if ((!fff)||(!f)||(!ff)) {
logger.error("异常类型:ElectronNumLabelException"+
"操作错误:标签NumberOfElectron或者NumberOfTracks或者ElementName不规范"+
"停止读取文件");
throw new ElectronNumLabelException("the label of 'NumberOfElectron ::= ' or 'NumberOfTracks ::= '"
+ " or 'ElementName ::= ' does'n match!");
}
if (tracks.length-1 != trackNum) {
logger.error("异常类型:AtomTrackNumMatchException"+
"操作错误:输入的TrackNumber和电子所在轨道总和不匹配"+
"停止读取文件");
throw new AtomTrackNumMatchException("the number of tracks does'n match!");
}
if ((fff)&&(ff)&&(f)) {
CentralObject central = CentralObject.createAtom(atomName);
super.addCentralObject((L)central);
}
}
@Override
public boolean check() {
return true;
}
@Override
public int getInfo(E e) {
throw new UnsupportedOperationException();
}
}
如此实现每当异常发生时日志有记录。