[JAVA] SimpleLogger 클래스
로그 쓰기용 자바 클래스.
주요 기능은 현재 위치에 log 폴더를 만들고 그 안에 로그 파일을 쓰는 것이다.
클래스 하나만 갖다 놓으면 로그를 기록할 수 있게 간단한 형태로 만들어보았다.
———-
package com.bb.simpleset
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Calendar;
public class SimpleLogger {
/**
* Exception 객체의 trace 를 로그로 쓴다.
* @param paramException
*/
public static void printLog(Exception paramException) {
try {
printLog(convExceptionToString(paramException));
} catch (Exception e) {
// 로그 쓰기 실패
e.printStackTrace();
}
}
/**
* 문자열을 로그로 쓴다.
* @param str
*/
public static void printLog(String str) {
try {
if (str == null) {
str = “”;
}
ArrayList<String> strList = new ArrayList<String>();
strList.add(str);
printLog(strList);
} catch (Exception e) {
// 로그 쓰기 실패
e.printStackTrace();
}
}
/**
* 문자열 리스트를 로그로 쓴다.
* @param stringList
*/
public static void printLog(ArrayList<String> stringList) {
try {
String filePath = createLogFolder();
writeLogFile(filePath, stringList, true);
} catch (Exception e) {
// 로그 쓰기 실패
e.printStackTrace();
}
}
/**
* 폴더를 생성한다.
*
* @return
* @throws Exception
*/
private static synchronized String createLogFolder() throws Exception {
String currentDate = getCurrentDate();
String year = currentDate.substring(0, 4);
String month = currentDate.substring(4, 6);
String folderPath = “log/” + year + “/” + month;
File dirObj = new File(folderPath);
if (!dirObj.exists()) {
dirObj.mkdirs();
}
String fileName = currentDate + “.log”;
String filePath = folderPath + “/” + fileName;
File logFile = new File(filePath);
if (!logFile.exists()) {
logFile.createNewFile();
}
return filePath;
}
/**
* 로그 쓰기 공통
*
* @param filePath
* @param stringList
* @param bAppend
* @return
* @throws IOException
* @throws Exception
*/
private static synchronized boolean writeLogFile(String filePath, ArrayList<String> stringList, boolean bAppend) throws IOException, Exception {
if (filePath == null || filePath.length() == 0) {
return false;
}
File file = new File(filePath);
boolean bWrite = false;
FileOutputStream fileOutputStream = null;
OutputStreamWriter outputStreamWriter = null;
BufferedWriter bufferedWriter = null;
try {
fileOutputStream = new FileOutputStream(file, bAppend);
outputStreamWriter = new OutputStreamWriter(fileOutputStream, “UTF-8”);
bufferedWriter = new BufferedWriter(outputStreamWriter);
if (stringList != null && stringList.size() > 0) {
String oneLine = null;
String currentDateTime = getCurrentDateTimeWithSlash();
bufferedWriter.write(“[” + currentDateTime + “] “);
System.out.print(“[” + currentDateTime + “] “);
int lineCount = stringList.size();
for (int i=0; i<lineCount; i++) {
oneLine = stringList.get(i);
if (oneLine == null) {
oneLine = “”;
}
bufferedWriter.write(oneLine, 0, oneLine.length());
bufferedWriter.newLine();
System.out.println(oneLine);
}
}
bWrite = true;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
} finally {
close(bufferedWriter);
close(outputStreamWriter);
close(fileOutputStream);
}
return bWrite;
}
private static void close(BufferedWriter bufferedWriter) {
try {
if (bufferedWriter != null) {
bufferedWriter.close();
}
} catch (Exception e) {
// 무시
} finally {
bufferedWriter = null;
}
}
private static void close(OutputStreamWriter outputStreamWriter) {
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
} catch (Exception e) {
// 무시
} finally {
outputStreamWriter = null;
}
}
private static void close(FileOutputStream fileOutputStream) {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e) {
// 무시
} finally {
fileOutputStream = null;
}
}
/**
* Exception 객체의 stackTrace 를 얻어서 문자열로 변환하여 리턴한다.
*
* @param e
* @return
*/
public static String convExceptionToString(Exception e) {
if (e == null) {
return “”;
}
StringBuffer buff = new StringBuffer();
// java.lang.ArithmeticException: / by zero
buff.append(e.getClass().getName() + “: ” + e.getMessage() + “\n”);
StackTraceElement[] trace = e.getStackTrace();
if (trace != null && trace.length > 0) {
StackTraceElement stack = null;
for (int i=0; i<trace.length; i++) {
stack = trace[i];
String str = stack.toString();
// at Tester.aa(Tester.java:23)
// at Tester.main(Tester.java:8)
buff.append(“at ” + str + “\n”);
}
}
return buff.toString();
}
/**
* 현재 날짜를 가져온다. (YYYYMMDD)
*
* @return
*/
private static String getCurrentDate() {
Calendar cal = Calendar.getInstance();
StringBuffer today = new StringBuffer();
today.append(String.format(“%04d”, cal.get(cal.YEAR)));
today.append(String.format(“%02d”, cal.get(cal.MONTH) + 1));
today.append(String.format(“%02d”, cal.get(cal.DAY_OF_MONTH)));
return today.toString();
}
/**
* 현재 날짜와 시간을 슬래시 포함한 문자열로 가져온다. (0000/00/00 00:00:00)
*
* @return
*/
private static String getCurrentDateTimeWithSlash() {
Calendar cal = Calendar.getInstance();
StringBuffer today = new StringBuffer();
today.append(String.format(“%04d”, cal.get(cal.YEAR)));
today.append(“/”);
today.append(String.format(“%02d”, cal.get(cal.MONTH) + 1));
today.append(“/”);
today.append(String.format(“%02d”, cal.get(cal.DAY_OF_MONTH)));
today.append(” “);
today.append(String.format(“%02d”, cal.get(cal.HOUR_OF_DAY)));
today.append(“:”);
today.append(String.format(“%02d”, cal.get(cal.MINUTE)));
today.append(“:”);
today.append(String.format(“%02d”, cal.get(cal.SECOND)));
return today.toString();
}
}