java++记录+运行_记录java+testng运行selenium(三)---xml、ini、excel、日志等配置
发布日期:2021-06-24 16:17:54 浏览次数:3 分类:技术文章

本文共 21229 字,大约阅读时间需要 70 分钟。

一: ini文件

ini目前只用处存储浏览类型及需要打开的url,ini文件放在configs文件夹下面。

读取ini代码如下:

1 packagetoolskit.documents;2

3 import java.io.*;4 import java.util.*;5

6 /**

7 * @ ClassName: ReadIni8 * @ Author: DingDong9 * @ Date: 2019/8/23 10:5710 * @ Version: 1.011 * @ desc: 读取ini后缀名的文件12 */

13

14 public classReadIni {15

16 /**

17 * 去除ini文件中的注释,以";"或"#"开头,顺便去除UTF-8等文件的BOM头18 *@paramsource19 *@return

20 */

21 private staticString removeIniComments(String source) {22

23 String result =source;24

25 if (result.contains(";")) {26 result = result.substring(0, result.indexOf(";"));27 }28

29 if (result.contains("#")) {30 result = result.substring(0, result.indexOf("#"));31 }32

33 returnresult.trim();34 }35

36

37 public static MapreadIni(String filename,String filepath) {38 Map> listResult = new HashMap<>();39 Map result = newHashMap();40 String globalSection = "global";41

42 if (filepath.equalsIgnoreCase("") || filepath == null){43 filepath = ".\\src\\main\\java\\configs\\";44 filename = filepath +filename;45 }46 File file = newFile(filename);47 BufferedReader reader = null;48 try{49 reader = new BufferedReader(new InputStreamReader(newFileInputStream(file)));50 String str = null;51 String currentSection = globalSection; //处理缺省的section

52 List currentProperties = new ArrayList<>();53 boolean lineContinued = false;54 String tempStr = null;55

56 //一次读入一行(非空),直到读入null为文件结束57 //先全部放到listResult中

58 while ((str = reader.readLine()) != null) {59 str = removeIniComments(str).trim(); //去掉尾部的注释、去掉首尾空格

60

61 if ("".equals(str) || str == null) {62 continue;63 }64

65 //如果前一行包括了连接符'\'

66 if (lineContinued == true) {67 str = tempStr +str;68 }69

70 //处理行连接符'\'

71 if (str.endsWith("\\")) {72 lineContinued = true;73 tempStr = str.substring(0, str.length() - 1);74 continue;75 } else{76 lineContinued = false;77 }78

79 //是否一个新section开始了

80 if (str.startsWith("[") && str.endsWith("]")) {81 String newSection = str.substring(1, str.length() - 1).trim();82

83 //如果新section不是现在的section,则把当前section存进listResult中

84 if (!currentSection.equals(newSection)) {85 listResult.put(currentSection, currentProperties);86 currentSection =newSection;87

88 //新section是否重复的section89 //如果是,则使用原来的list来存放properties90 //如果不是,则new一个List来存放properties

91 currentProperties =listResult.get(currentSection);92 if (currentProperties == null) {93 currentProperties = new ArrayList<>();94 }95 }96 } else{97 currentProperties.add(str);98 }99 }100 //把最后一个section存进listResult中

101 listResult.put(currentSection, currentProperties);102

103 reader.close();104

105

106 } catch(IOException e) {107 e.printStackTrace();108 } finally{109 if (reader != null) {110 try{111 reader.close();112 } catch(IOException e1) {113 }114 }115 }116

117

118 //整理拆开name=value对,并存放到MAP中:119 //从listResult中,看各个list中的元素是否包含等号“=”,如果包含,则拆开并放到Map中120 //整理后,把结果放进result中

121 for(String key : listResult.keySet()) {122 List tempList =listResult.get(key);123

124 //空section不放到结果里面

125 if (tempList == null || tempList.size() == 0) {126 continue;127 }128

129 if (tempList.get(0).contains("=")) { //name=value对,存放在MAP里面

130 Map properties = new HashMap<>();131 for(String s : tempList) {132 int delimiterPos = s.indexOf("=");133 //处理等号前后的空格

134 properties.put(s.substring(0, delimiterPos).trim(), s.substring(delimiterPos + 1, s.length()).trim());135 }136 result.put(key, properties);137 } else { //只有value,则获取原来的list

138 result.put(key, listResult.get(key));139 }140 }141 returnresult;142 }143

144 }

二: xml文件读取

xml文件主要存储excel所在路径以及用例类所对应的sheet名

代码如下:

importjava.util.ArrayList;importjava.util.HashMap;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importorg.dom4j.Document;importorg.dom4j.DocumentException;importorg.dom4j.Element;importorg.dom4j.io.SAXReader;/*** @ ClassName: toolskit.documents

* @ Author: DingDong

* @ Date: 2019/10/21 14:36

* @ Version: 1.0

* @ desc:*/

public classXmlUtil {public staticList getXmlComent(String path){//获取xml文件完全路径

System.out.println("xml·path"+path);

List contList=newArrayList();//dom4j中读取xml文件的方法

SAXReader saxR=newSAXReader();try{

Document doc=saxR.read(path);//存放顶结点

Element eleroot=doc.getRootElement();//parMap,存放顶结点下一级结点

Map parMap=null;

Map sonMap=null;for(Iterator i=eleroot.elementIterator();i.hasNext();){//parMap中存放的结点的子结点

parMap=newHashMap();

sonMap=newHashMap();

Element elepar=(Element)i.next();for(Iterator j=elepar.elementIterator();j.hasNext();){

Element eleSon=(Element)j.next();

System.out.println("+++++"+eleSon.getName()+" "+eleSon.getText());

sonMap.put(eleSon.getName(), eleSon.getText());

}

parMap.put(elepar.getName(),sonMap);

System.out.println("*****"+elepar.getName() +"*********" +sonMap);

contList.add(parMap);

}

}catch(DocumentException e) {

e.printStackTrace();

}returncontList;

}

}

其中parMap和sonMap要在for里面清空已有的内容,不然contList存储的数据都是重复的

四:excel文件读写

ExcelOperating作为父类,用于区分文件类型及文件是否存在

ReadExcel:用于用户读取excel的内容并存在Map里面然后返回

WriteExcel :让用户将输入写入excel里面

ExcelOperating代码如下:

1 packagetoolskit.documents;2

3 import java.io.*;4 importjava.text.DecimalFormat;5 importjava.text.SimpleDateFormat;6 importjava.util.Date;7

8 importorg.apache.commons.io.IOCase;9 importorg.apache.poi.hssf.usermodel.HSSFWorkbook;10 import org.apache.poi.ss.usermodel.*;11

12 importorg.apache.poi.xssf.usermodel.XSSFWorkbook;13 importorg.apache.poi.ss.usermodel.DateUtil;14

15

16

17

18

19 public classExcelOperating {20

21 private final String XLS_VERSION = "xls";22 private final String XLSX_VERSION = "xlsx";23

24 /**

25 * 判断Excel的版本,获取Workbook26 *@paramfileName 文件名27 *@returnsheet对象28 */

29 publicWorkbook distinguishWorkbook(String fileName) {30 Workbook workbook = null;31 InputStream is = null;32 try{33 File file = newFile(fileName);34 is = newFileInputStream(file);35

36 if(IOCase.SENSITIVE.checkEndsWith(fileName, XLS_VERSION)) {37

38 workbook = newHSSFWorkbook(is);39

40 } else if(IOCase.SENSITIVE.checkEndsWith(fileName, XLSX_VERSION)) {41

42 workbook = newXSSFWorkbook(is);43

44 } else{45 System.out.println("该文件不是excle表格:" +fileName);46

47 }48 } catch(FileNotFoundException e) {49 System.out.println(">>>>>>>>>> 读取excel文件时出错了!!!");50 e.printStackTrace();51 } catch(IOException e) {52 System.out.println(">>>>>>>>>> 读取excel文件时出错了!!!");53 e.printStackTrace();54 }finally{55 if (is != null) {56 try{57 is.close();58 } catch(IOException e) {59 e.printStackTrace();60 }61 }62 }63 returnworkbook;64 }65

66

67 publicString getIntTypeValue(Cell cell) {68 String cellValue = "";69 double value =cell.getNumericCellValue();70 if (cell.getCellStyle().getDataFormat() == 176) {71

72 //处理自定义日期格式:M月D日(通过判断单元格的格式id解决,ID的值是58)

73 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");74 Date date =DateUtil.getJavaDate(value);75 cellValue =sdf.format(date);76

77 } else{78 CellStyle style =cell.getCellStyle();79 DecimalFormat format = newDecimalFormat();80 String temp =style.getDataFormatString();81

82 //把数字当成String来读,避免出现1读成1.0的情况.这个方式没这么灵活83 //if (cell.getCellType() == CellType.NUMERIC) {84 //cell.setCellType(CellType.STRING);85 //}86

87 //单元格设置成常规

88 if (temp.equals("General")) {89 format.applyPattern("#");90 }91 cellValue =format.format(value);92 }93 returncellValue;94 }95

96 /**

97 * 判断获取当前内容的格式,然后进行返回内容98 * 把单元格的内容转为字符串99 * 高版本的import org.apache.poi.ss.usermodel.CellType变为了import org.apache.poi.ss.usermodel.Cell;100 * 同时cellRowName.setCellType(CellType.STRING);变为了cellRowName.setCellType(Cell.CELL_TYPE_STRING);101 * 并且xssfCell.getCellTypeEnum()变成xssfCell.getCellType()102 * CellType 类型 值103 * NUMERIC 数值型 0104 * STRING 字符串型 1105 * FORMULA 公式型 2106 * BLANK 空值 3107 * BOOLEAN 布尔型 4108 * ERROR 错误 5109 *@paramcell 单元格110 *@return字符串111 */

112 @SuppressWarnings("deprecation")113 publicString getCellValue(Cell cell) {114 String cellValue = "";115 if (cell == null) {116 returncellValue;117 }118

119 //判断数据的类型,低版本中switch里面的case写法不一样。

120 CellType cellType =cell.getCellType();121

122 switch(cellType) {123 case NUMERIC: //数字

124 cellValue =getIntTypeValue(cell);125 break;126 case STRING: //字符串

127 cellValue =String.valueOf(cell.getStringCellValue());128 break;129 case BOOLEAN: //Boolean

130 cellValue =String.valueOf(cell.getBooleanCellValue());131

132 break;133 case FORMULA: //公式

134 cellValue =String.valueOf(cell.getCellFormula());135 break;136 case BLANK: //空值

137 cellValue = "";138 break;139 case ERROR: //故障

140 cellValue = "非法字符";141 break;142 case _NONE: //故障

143 cellValue = "非法字符";144 break;145 default:146 cellValue = "未知类型";147 break;148 }149 returncellValue;150 }151

152 }

ReadExcel代码如下:

1 packagetoolskit.documents;2

3 import java.io.*;4 import java.util.*;5

6 import org.apache.poi.ss.usermodel.*;7

8

9 public class ReadExcel extendsExcelOperating {10 //public static void main(String[] args) {11 //ReadExcel re = new ReadExcel();12 //String load = "C:\\Users\\LGYY-USER\\Desktop\\红包发放.xlsx";13

14

15 //方式一: 指定sheet来读取16 //List> excelList = re.readExcel(load, "登录");17 //System.out.println("从excel读取数据并开始使用:");18 //for (Map list : excelList) {19 //System.out.println(list);20 //for (Map.Entry entry : list.entrySet()) {21 //System.out.println(entry.getValue());22 //}23 //System.out.println();24 //}25

26 //方式二: 读取单个文件,单行数据27 //Map stringStringMap = re.singleReadXlsx(load, "登录", 2);28 //System.out.println(stringStringMap);29 //for(Map.Entry entry : stringStringMap.entrySet()){30 //System.out.print("Key = "+entry.getKey()+",value="+entry.getValue() + "\n");31 //}32

33 //方式三: 读取全部sheet的数据34 //List> lists = re.wholeReadXlsx(load);35 //for (Map i : lists) {36 //System.out.print(i);37 //}38

39 //}

40

41 /**

42 * 通过Workbook来读取excle表格上的数据43 *44 *@paramload 文件所在路径45 *@return获取到的数据46 */

47 public List>wholeReadXlsx(String load) {48 //excel中第几列 : 对应的表头

49 Map colAndNameMap = new HashMap();50 List> resultList = new ArrayList>();51 Workbook wb = null;52 try{53 wb =distinguishWorkbook(load);54 for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {55 //获取sheet数据

56 Sheet st =wb.getSheetAt(sheetIndex);57 //遍历一个sheet中每一行

58 for (int rowIndex = 0; rowIndex <= st.getLastRowNum(); rowIndex++) {59 //表头:值

60 Map nameAndValMap = new HashMap();61 //获取到一行数据

62 Row row =st.getRow(rowIndex);63 for (int cellIndex = 0; cellIndex < row.getPhysicalNumberOfCells(); cellIndex++) {64

65 if (rowIndex == 0) {66 colAndNameMap.put(cellIndex, row.getCell(cellIndex).getStringCellValue());67 } else if (!colAndNameMap.isEmpty()) {68 nameAndValMap.put(cellIndex, getCellValue(row.getCell(cellIndex)));69 }70 }71 if (!nameAndValMap.isEmpty()) {72 resultList.add(nameAndValMap);73 }74 }75 }76 returnresultList;77 } catch(Exception e) {78 System.out.println(">>>>>>>>>> 读取excel文件时出错了!!!");79 e.printStackTrace();80 } finally{81 try{82 wb.close();83 } catch(IOException e) {84 e.printStackTrace();85 }86 }87 return null;88 }89

90

91 /**

92 * 读取指定工作薄里的指定行的内容93 * load文档所在地94 * numSheet当前文档中所读写的工作薄95 * rowNum当前工作薄中的第几个数据96 *@paramload 文件所在路径97 *@paramsheetName sheet表格名字98 *@paramrowNum 指定行数99 *@return找到的全部数据100 */

101 public Map singleReadXlsx(String load, String sheetName, introwNum) {102 Workbook xssfWorkbook =distinguishWorkbook(load);103 Map aMap = new HashMap();104 Sheet xssfSheet;105 if (sheetName.equals("")) {106 //默认取第一个子表

107 xssfSheet = xssfWorkbook.getSheetAt(0);108 } else{109 xssfSheet =xssfWorkbook.getSheet(sheetName);110 }111

112 if (xssfSheet != null) {113 //获取指定行

114 Row xssfRow = xssfSheet.getRow(rowNum);//获取该行的全部数据

115 if (xssfRow != null) {116

117 int firstCellNum = (int) xssfRow.getFirstCellNum();//首列

118 int lastCellNum = (int) xssfRow.getLastCellNum();//最后一列

119

120 for (int col = firstCellNum; col < lastCellNum; col++) {121 String sEnum = col + "";122 aMap.put(sEnum, getCellValue(xssfRow.getCell(col)));123 }124 } else{125 System.out.println("xssfRow为空");126 }127 }128

129 returnaMap;130 }131

132

133 /**

134 * 指定表格中行的数据长度135 *@paramload 文件名136 *@paramnameSheet 表格名字137 *@return表格行的总数138 */

139 public intsingleXlsx(String load, String nameSheet) {140 int row = 0;141 //获取每一个工作薄

142 Sheet sheetAt =distinguishWorkbook(load).getSheet(nameSheet);143 if (sheetAt != null) {144 row =sheetAt.getLastRowNum();145 }146 returnrow;147

148 }149

150 /**

151 * 读取Excel文件中指定sheet的内容152 *153 *@paramload excel文件的所在路径154 *@paramsheetName sheet名字155 *@return以List返回excel中内容156 */

157 public List>readExcel(String load, String sheetName) {158

159 Workbook xssfWorkbook =distinguishWorkbook(load);160

161 //定义工作表

162 Sheet xssfSheet;163

164 if (sheetName.equals("")) {165 //默认取第一个子表

166 xssfSheet = xssfWorkbook.getSheetAt(0);167 } else{168 xssfSheet =xssfWorkbook.getSheet(sheetName);169 }170

171 List> list = new ArrayList>();172

173 //默认第一行为标题行,index = 0

174 Row titleRow = xssfSheet.getRow(0);175

176 //根据第一行返回该行中单元格的数量

177 int cellNumber =titleRow.getPhysicalNumberOfCells();178

179 //返回sheet标中行的总数

180 int rownumber =xssfSheet.getPhysicalNumberOfRows();181

182 //循环取每行的数据

183 for (int rowIndex = 1; rowIndex < rownumber; rowIndex++) {184 Row xssfRow =xssfSheet.getRow(rowIndex);185 if (xssfRow == null) {186 continue;187 }188

189 Map map = new LinkedHashMap();190

191 //循环取每个单元格(cell)的数据

192 for (int cellIndex = 0; cellIndex < cellNumber; cellIndex++) {193 Cell titleCell =titleRow.getCell(cellIndex);194 Cell xssfCell =xssfRow.getCell(cellIndex);195 map.put(getCellValue(titleCell), getCellValue(xssfCell));196 }197 list.add(map);198 }199 returnlist;200 }201

202 /**

203 * 把一个Map中的所有键和值分别放到一个list中,204 * 再把这两个list整个放到一个大的list里面,即 [ [key1,key2,key3...] , [value1,value2,value3...] ]205 *206 *@parammap 需要转换的map207 *@return已转换后的list208 */

209 public static ListconvertMapToList(Map map) {210 List list = new ArrayList();211 List key_list = new LinkedList();212 List value_list = new LinkedList();213

214 Set set =map.entrySet();215 Iterator> iter1 =set.iterator();216 while(iter1.hasNext()) {217 key_list.add(iter1.next().getKey());218 }219 list.add(key_list);220

221 Collection value =map.values();222 Iterator iter2 =value.iterator();223 while(iter2.hasNext()) {224 value_list.add(iter2.next());225 }226 list.add(value_list);227 returnlist;228 }229 }

WriteExcel写法如下:很少使用这个类

packagetoolskit.documents;import java.io.*;importjava.util.List;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.Workbook;importorg.apache.poi.xssf.usermodel.XSSFCell;importorg.apache.poi.xssf.usermodel.XSSFRow;importorg.apache.poi.xssf.usermodel.XSSFSheet;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;public class WriteExcel extendsExcelOperating{//当前文件已经存在

private String excelPath = "E:/MyFirstExcel.xlsx";//从第几行插入进去

private intinsertStartPointer;//根据工作薄名进行插入

privateString sheetName;//根据工作薄所在位置进行插入

private int sheetInsert = 0;public WriteExcel(String excelPath, int insertStartPointer, String sheetName, intsheetInsert) {this.excelPath =excelPath;this.insertStartPointer =insertStartPointer;this.sheetName =sheetName;this.sheetInsert =sheetInsert;

}publicWriteExcel() {

}/*** 总的入口方法*/

public static voidmain(String[] args){

WriteExcel crt= newWriteExcel();int i = new ReadExcel().singleXlsx(crt.excelPath, "sheet");

crt.insertStartPointer= i + 1;

crt.insertRows();

}/*** 在已有的Excel文件中插入一行新的数据的入口方法*/

public voidinsertRows() {

Workbook wb=returnWorkBookGivenFileHandle();//XSSFSheet sheet1 = wb.getSheet(sheetName);

sheetName =wb.getSheetName(sheetInsert);

Sheet sheet=wb.getSheet(sheetName);

Row row=createRow(sheet, insertStartPointer);

createCell(row);

saveExcel(wb);

}/*** 保存工作薄

*

*@paramwb*/

private voidsaveExcel(Workbook wb) {

FileOutputStream fileOut;try{

fileOut= newFileOutputStream(excelPath);

wb.write(fileOut);

fileOut.close();

}catch(FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}/*** 创建要出入的行中单元格

*

*@paramrow

*@return

*/

privateCell createCell(Row row) {

Cell cell= row.createCell((short) 0);

cell.setCellValue(999999);

row.createCell(1).setCellValue(1.2);

row.createCell(2).setCellValue("This is a string cell");returncell;

}/*** 得到一个已有的工作薄的POI对象

*

*@return

*/

privateWorkbook returnWorkBookGivenFileHandle() {

Workbook wb= null;

File f= newFile(excelPath);try{if (f != null) {

wb=distinguishWorkbook(excelPath);

}

}catch(Exception e) {return null;

}returnwb;

}/*** 找到需要插入的行数,并新建一个POI的row对象

*

*@paramsheet

*@paramrowIndex

*@return

*/

privateRow createRow(Sheet sheet, Integer rowIndex) {

Row row= null;if (sheet.getRow(rowIndex) != null) {int lastRowNo =sheet.getLastRowNum();

sheet.shiftRows(rowIndex, lastRowNo,1);

}

row=sheet.createRow(rowIndex);returnrow;

}/*** 把内容写入Excel

*

*@paramlist 传入要写的内容,此处以一个List内容为例,先把要写的内容放到一个list中

*@paramoutputStream 把输出流怼到要写入的Excel上,准备往里面写数据*/

public void writeExcel(Listlist, OutputStream outputStream) {//创建工作簿

XSSFWorkbook xssfWorkbook;

xssfWorkbook= newXSSFWorkbook();//创建工作表

XSSFSheet xssfSheet;

xssfSheet=xssfWorkbook.createSheet();//创建行

XSSFRow xssfRow;//创建列,即单元格Cell

XSSFCell xssfCell;//把List里面的数据写到excel中

for (int i = 0; i < list.size(); i++) {//从第一行开始写入

xssfRow =xssfSheet.createRow(i);//创建每个单元格Cell,即列的数据

List sub_list =list.get(i);for (int j = 0; j < sub_list.size(); j++) {

xssfCell= xssfRow.createCell(j); //创建单元格

xssfCell.setCellValue((String) sub_list.get(j)); //设置单元格内容

}

}//用输出流写到excel

try{

xssfWorkbook.write(outputStream);

outputStream.flush();

outputStream.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

五:日志输出

日志输出一般有两个方式:

1. 定义全局的System.out.println统一进行输出

2. 由log日志进行输出

由System.out.println输出的模板:

packagetoolskit;importjava.util.Iterator;importjava.util.List;importjava.util.Map;/*** @ ClassName: SystemOut

* @ Author: DingDong

* @ Date: 2019/8/13 11:33

* @ Version: 1.0

* @ desc:*/

public classSystemOut {public static voidtextStringOut(String data, String text) {

System.out.println(data+ ":" +text);

}public static voidtextStringOut(String status, String data, String text) {

System.out.println(status+ ":" + data + ":" +text);

}public static voidtextStringOut(String text) {

System.out.println(text);

}/*** 用例成功,并且编辑成功

*

*@parammassage 用例编号

*@paramparameter 用例输入的内容*/

public static voidcaseSuccess(String massage, String parameter) {

System.out.println(massage+ "用例执行成功,编辑内容为:" +parameter);

}/*** 编辑判断成功

*

*@parammassage 执行编号*/

public static voidcaseEditSuccess(String massage) {

System.out.println(massage+ "用例中的元素对象不需要编辑,程序判断成功。。");

}/*** 用例执行成功

*

*@parammassage*/

public static voidcaseSuccess(String massage) {

System.out.println(massage+ "用例执行成功");

}/*** 用例执行失败,并且打印出输入信息

*

*@parammassage*/

public static voidcaseFail(String massage) {

System.out.println(massage+ "用例执行失败。。。。");

}/*** 不需要进行编辑时发生失败

*

*@parammassage 用例编号*/

public static voidcaseEditFail(String massage) {

System.out.println(massage+ "用例中的元素对象不需要编辑,程序判断失败。");

}public static voidcaseFail(String massage, String parameter) {

System.out.println(massage+ "用例执行失败,编辑内容为:" +parameter);

}/***@paramli*/

public static void getStringOut(List li) throwsInterruptedException {

textStringOut("打印list开始" +li.size());for (int i = 0; i < li.size(); i++) {

textStringOut(li.get(i).toString());

}

}public static void getStringOut(Map aMap) throwsInterruptedException {

textStringOut("打印list开始" +aMap.size());

Iterator> iterator =aMap.entrySet().iterator();while(iterator.hasNext()) {

Map.Entry next =iterator.next();

System.out.println("Key = " + next.getKey() + ", Value = " +next.getValue());

}

}

}

log日志输出:

1. 在resources文件夹下面创建以下两个文件:common-logging.properties 和 log4j.properties

2. 配置两个dependency,分别是commons-logging 和 log4j

common-logging.properties 里面内容为:

org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

log4j.properties 里面内容为:

#设置logger级别DEBUG、INFO、WRNING、ERROR和输出格式A、B、C或D

log4j.rootLogger=debug , stdout , D , E

### 输出INFO级别以上的日志到控制台 ###

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.out

log4j.appender.stdout.Threshold=DEBUG

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### 输出到日志文件 ###

log4j.appender.D=org.apache.log4j.DailyRollingFileAppender

log4j.appender.D.File=E:/logs/log.log

log4j.appender.D.Append=true## 输出DEBUG级别以上的日志

log4j.appender.D.Threshold=DEBUG

log4j.appender.D.layout=org.apache.log4j.PatternLayout

log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %c{1}:%L %m%n

### 保存异常信息到单独文件 ###

log4j.appender.E=org.apache.log4j.DailyRollingFileAppender

## 异常日志文件名

log4j.appender.E.File=E:/logs/error.log

log4j.appender.E.Append=true## 只输出ERROR级别以上的日志!!!log4j.appender.E.Threshold=ERROR

log4j.appender.E.layout=org.apache.log4j.PatternLayout

log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

pom文件配置:dependency

commons-logging

commons-logging

1.2

log4j

log4j

1.2.17

log代码:

packagetoolskit;importorg.apache.log4j.Logger;/*** @ ClassName: InformationLog

* @ Author: DingDong

* @ Date: 2019/8/9 17:39

* @ Version: 1.0

* @ desc:*/

public classInformationLog {protected static final Logger logger = Logger.getLogger(InformationLog.class);public static voidinputLogInfo(String infoData) {

logger.info(infoData);

}public static voidinputLogDebug(String infoData) {

logger.debug(infoData);

}public static voidinputLogWarn(String infoData) {

logger.warn(infoData);

}public static voidinputLogError(String infoData) {

logger.error(infoData);

}public static voidinputLogFatal(String infoData) {

logger.fatal(infoData);

}

}

说明:

定义文件地址的时候,都是写死;文件地址这边写死(动态又高级的写法不懂如何编写)

转载地址:https://blog.csdn.net/weixin_33765959/article/details/114834647 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:mysql居左查询abcd_MySql速查手册
下一篇:java约瑟夫环pta上_cdoj525-猴子选大王 (约瑟夫环)

发表评论

最新留言

很好
[***.229.124.182]2024年04月25日 01时47分05秒