프로젝트 하다보면 Release 모드에서 테스트 하다 Crash 발생 할경우 확인할 방법이 없어서 Crash 발생시 디테일한 내용을

파일로 저장하는 Debug 기능임. 

 

public class ExceptionHandler implements  Thread.UncaughtExceptionHandler {
    private Context context;

    private boolean isLogFile = false;

    public ExceptionHandler(Context context) {
        this.context = context;
    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        if (!isLogFile) {
            // Error 내용
            DLog.e(new Exception(), e.getMessage());

            // Trace 추적 로그
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);

            file(context, "ERROR", e.getMessage() + "\n\n"+ sw.toString());

            isLogFile = true;
        }

        Thread.getDefaultUncaughtExceptionHandler().uncaughtException(t, e);
    }

    /**
     * Error 로그 파일로 저장
     * 파일 저장 위치는 Download 폴더
     * */
    private void file(Context context, String check, String msg) {
        String baseFolder;
        // check if external storage is available
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            baseFolder = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
        }
        // revert to using internal storage (not sure if there's an equivalent to the above)
        else {
            baseFolder = context.getFilesDir().getAbsolutePath();
        }

        SimpleDateFormat sdf2 = null;
        Date date = new Date();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            sdf2 = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        }

        String filename = check + "_" + sdf2.format(date) + ".txt";

        File file = new File(baseFolder + File.separator + filename);
        file.setWritable(true);
        file.setReadable(true);
        file.getParentFile().mkdirs();
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(msg.getBytes());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            DLog.e(new Exception(), e.getMessage());
        }
    }
}

 

[적용]

public class App extends Application {
	@Override
    public void onCreate() {
        super.onCreate();
        
        // App 오류 시 Exception Handler 오류내용 휴대폰의 Downlaod 폴더에 저장 처리
        if (BuildConfig.DEBUG_MODE) {
            Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
        }
    }
}

+ Recent posts