Android Log File Write WriteLogToSDCard(Context context, String tag, String logFileName, String msg)

Here you can find the source of WriteLogToSDCard(Context context, String tag, String logFileName, String msg)

Description

Write Log To SD Card

Declaration

public static void WriteLogToSDCard(Context context, String tag,
            String logFileName, String msg) 

Method Source Code

//package com.java2s;
import android.content.Context;

import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

public class Main {
    public static final boolean DEBUG_DEVELOPER_MODE = false;
    private static final boolean WRITE_LOG_SDCARD_SWITCH = true;

    public static void WriteLogToSDCard(Context context, String tag,
            String logFileName, String msg) {
        if (DEBUG_DEVELOPER_MODE) {
            Log.i(tag, msg);//w w  w.jav  a 2  s.  c  o m
        }
        if (WRITE_LOG_SDCARD_SWITCH
                && android.os.Environment.getExternalStorageState().equals(
                        android.os.Environment.MEDIA_MOUNTED)) {
            try {

                File dirPath = context.getExternalCacheDir();
                if (dirPath == null) {
                    return;
                }

                if (!dirPath.exists() || !dirPath.isDirectory()) {
                    dirPath.mkdirs();
                }

                File savefile = new File(dirPath, logFileName);
                if (!savefile.exists()) {
                    savefile.createNewFile();
                } else {
                    long length = savefile.length();
                    if (length > 2 * 1024 * 1024) {
                        savefile.delete();
                        savefile.createNewFile();
                    }
                }
                Calendar CD = Calendar.getInstance();
                int YY = CD.get(Calendar.YEAR);
                int MM = CD.get(Calendar.MONTH) + 1;
                int DD = CD.get(Calendar.DATE);
                int HH = CD.get(Calendar.HOUR_OF_DAY);
                int NN = CD.get(Calendar.MINUTE);
                int SS = CD.get(Calendar.SECOND);
                String logmsg = "";
                logmsg += "[";
                String szTime = "";
                szTime = String.format("%04d-%02d-%02d %02d:%02d:%02d", YY,
                        MM, DD, HH, NN, SS);
                logmsg += szTime;
                logmsg += "]";
                logmsg += msg;
                logmsg += "\r\n";
                FileOutputStream out = new FileOutputStream(savefile, true);
                out.write(logmsg.getBytes());
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. writeLog(File logFile, String tag, String message, Throwable tr)