728x90
반응형
앱이 백그라운드에서 돌거나, QA를 하면서 나왔던 에러를 다시 구현할때 어려움이 있어서,
앱내에 로그파일을 남겨야겠다고 생각했다.
dev 와 staging에서만 사용하고, release 모드에선 해당 기능을 숨기거나, 앱내 폴더로 숨길 예정이다.
해당 코드는
public class LogFileWriter {
private static final String TAG = "LogFileWriter";
private static final String LOG_FILE_NAME = "애플리케이션_log.txt";
public static void writeLogToFile(String message) {
String logText = getCurrentTimestamp() + " - " + message + "\n";
// 외부 저장소의 앱 디렉토리 경로 가져오기
String appDirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/애플리케이션";
File appDir = new File(appDirPath);
// 앱 디렉토리가 없으면 생성
if (!appDir.exists()) {
appDir.mkdirs();
}
// 로그 파일 생성 또는 열기
File logFile = new File(appDir, LOG_FILE_NAME);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(logFile, true); // 이어쓰기 모드로 파일 열기
fos.write(logText.getBytes());
} catch (IOException e) {
Log.e(TAG, "Error writing log to file: " + e.getMessage());
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
Log.e(TAG, "Error closing file output stream: " + e.getMessage());
}
}
}
}
private static String getCurrentTimestamp() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date now = new Date();
return sdf.format(now);
}
}
이고 로그를 기록하고 싶은 try catch문에서 사용하면 된다
728x90
반응형