White Whale Studio

[Android] File Log Write 본문

IT Engineering/Android 혹은 Java

[Android] File Log Write

glorymind 2018. 8. 28. 15:46
반응형

안드로이드에서 파일 형태로 로그를 남기고 싶을 때 사용하는 코드입니다.

저도 스택오버플로에서 보고 일부 수정해서 정리했습니다.


사용할때는 LogHelper 클래스를 선언하고 불러다 쓰면 되겠네요


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import android.os.Environment;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
 
public class LogHelper {
 
//// 파일 위치 지정
    public static String LogFilePath = Environment.getExternalStorageDirectory()+"/dbTemp/log.file";
 
    public void Log(String text)
    {
        File logFile = new File(LogFilePath);
        if (!logFile.exists())
        {
            try
            {
                logFile.createNewFile(); //// 파일이 없는 경우 생성하고
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try
        {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat mdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String strDate = mdformat.format(calendar.getTime()); //// 현재 일시를 가져와서 함께 기록
 
            //BufferedWriter for performance, true to set append to file flag
            BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
            buf.append("[" + strDate + "]" + text);
            buf.newLine();
            buf.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
 
cs


반응형
Comments