1. 程式人生 > >伺服器介面呼叫日誌檔案記錄(有格式)

伺服器介面呼叫日誌檔案記錄(有格式)

/**
 * 
 * @Title: writeLocationLog
 * @Description: 伺服器上寫入操作日誌
 * @param type  "input"表示入參,“output”表示出參
 * @param xml   具體的出入參資訊
 * @param TransNo 當是入參時一定要傳入對應的功能號,出參直接傳“”即可
 * @param JGID  當前的jgid
 * @throws ModelDataOperationException     
 * @return: void    
 * @throws
 */
public void writeLocationLog(String type, String xml, String TransNo, String JGID) throws ModelDataOperationException {
	String dirPath = "D:/PhisSZybLog/" + JGID;
	Date nowDate = new Date();
	SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMdd");
	SimpleDateFormat sdfLogTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String fileName = sdfFileName.format(nowDate);
	String logTime = sdfLogTime.format(nowDate);
	String filePath = dirPath + "/" + fileName + "yblog.txt";


	File dirFile = new File(dirPath);
	if (!dirFile.exists()) // 日誌資料夾不存在 怎建立
	{
		dirFile.mkdirs();
	}
	File file = new File(filePath);
	try {
		file.createNewFile(); // 此方法返回true,如果指定的檔案不存在,並已成功建立。如果該檔案存在,該方法返回false。
	} catch (IOException e) {
		MedicineUtils.throwsException(logger, "建立日誌記錄檔案失敗,請重新操作或聯絡管理員", e);
	}
	FileWriter fileWriter = null; // 在try程式碼塊之前定義fw確保在後面的try程式碼塊中能識別fw
	BufferedWriter bufferedWriter = null;
	// 開始書寫日誌檔案
	if (type.equals("input")) {
		// 記事本不識別“\n”語句,換行用“\r\n”
		String inputInfo = logTime + " --> JYBH: " + TransNo + "\r\n" + // 第一行日誌
				logTime + " --> Input:  " + xml + "\r\n";
		try {
			fileWriter = new FileWriter(filePath, true); // 傳遞一個true引數,代表不覆蓋已有的檔案。並在已有檔案的末尾處進行資料續寫
			bufferedWriter = new BufferedWriter(fileWriter);
			bufferedWriter.write(inputInfo);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferedWriter != null) {
					bufferedWriter.close();
				}
				if (fileWriter != null) {
					fileWriter.close(); // 重新整理並關閉檔案操作
				}
			} catch (IOException e) {
				MedicineUtils.throwsException(logger, "醫保記錄本地入參日誌檔案失敗,請重新操作或聯絡管理員", e);
			}
		}


	} else if (type.equals("output")) {
		// 記事本不識別“\n”語句,換行用“\r\n”
		String inputInfo = logTime + " --> Output: " + xml + "\r\n\r\n";
		try {
			fileWriter = new FileWriter(filePath, true); // 傳遞一個true引數,代表不覆蓋已有的檔案。並在已有檔案的末尾處進行資料續寫
			bufferedWriter = new BufferedWriter(fileWriter);
			bufferedWriter.write(inputInfo);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferedWriter != null) {
					bufferedWriter.close();
				}
				if (fileWriter != null) {
					fileWriter.close(); // 重新整理並關閉檔案操作
				}
			} catch (IOException e) {
				MedicineUtils.throwsException(logger, "醫保記錄本地出參日誌檔案失敗,請重新操作或聯絡管理員", e);
			}
		}
	}
}