Android應用如何巧妙合理的控制Log

Log是開發人員調試很重要的檢查點,所以呢,巧妙控制Log 是優秀碼農必須掌握好的技能之一!

第一步:寫過Util工具類,如下:

public class Utils {
   /**
     * 用來獲取Application meta data(這個在AndroidManifest中設置)
     */
    public static Object getApplicationMeta(String key) {
        Object applicationMeta = null;
        try {
            ApplicationInfo applicationInfo  = getPackageInfo().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            if(applicationInfo != null) {
                applicationMeta = applicationInfo.metaData.get(key);
            }
        } catch (NameNotFoundException e) {
            L.e("can not found the meta in the application attributes:"+key);
        }
        return applicationMeta;
    }
}

第二步:設置debug開關

public class AppConfigs {
	//設定一個debug開關,控制是否打印log
    private static boolean init = false;

    private static boolean mDebug = false;

    public static void loadConfig() {
        if(!init) {
            //load the debug switch
            Object debug = Utils.getApplicationMeta("debug");
            if(debug!=null) {
                try {
                    mDebug =  (Boolean)debug;
                } catch (Exception e) {
                    L.e("debug tag is error");
                }
            }
            init = true;
        }
    }

    public static boolean isDebug() {
        if(!init) {
            loadConfig();
        }
        return mDebug;
    }
}

第三步:重寫Log的打印方法,以及保存名稱:如 log_20140228

public class L {
    private static final String TAG = Constants.APP_NAME;
    /**
     * log文件名字
     */
    public static final String filename= Constants.LOG_DIR
            + File.separator + "log";

	/**
	 *根據Log不同等級
	 */

    public static void v(String text) {
        if (AppConfigs.isDebug()) {
            Log.v(TAG, text);
            write(text, Log.VERBOSE);
        }
    }

    public static void d(String text) {
        if (AppConfigs.isDebug()) {
            Log.d(TAG, text);
            write(text, Log.DEBUG);
        }
    }

    public static void i(String text) {
        if (AppConfigs.isDebug()) {
            Log.i(TAG, text);
            write(text, Log.INFO);
        }
    }

    public static void w(String text) {
        if (AppConfigs.isDebug()) {
            Log.w(TAG, text);
            write(text, Log.WARN);
        }
    }

    public static void e(String text) {
        if (AppConfigs.isDebug()) {
            Log.e(TAG, text);
            write(text, Log.ERROR);
        }
    }

    public static void e(String text, Throwable throwable) {
        StackTraceElement[] elements = throwable.getStackTrace();
        for (StackTraceElement e : elements) {
            e(e.toString());
        }
    }

    /**
     * 將Log寫到日志文件中
     * @param text
     * @param level
     */
    private static synchronized void write(String text, int level) {
        StringBuilder sb = new StringBuilder();
        sb.append("["
                + DateUtil.toTime(System.currentTimeMillis(),
                        DateUtil.DATE_FORMATE_ALL) + "]");
        switch (level) {
        case Log.VERBOSE:
            sb.append("[V]\t");
            break;
        case Log.DEBUG:
            sb.append("[D]\t");
            break;
        case Log.INFO:
            sb.append("[I]\t");
            break;
        case Log.WARN:
            sb.append("[W]\t");
            break;
        case Log.ERROR:
            sb.append("[E]\t");
            break;
        }
		//可以任意的訪問文件的任何地方
        RandomAccessFile raf = null;
        try {
            String fileName =filename+ "_"
                    + DateUtil.toTime(System.currentTimeMillis(),
                            DateUtil.DATE_DEFAULT_FORMATE);
            File logFile = new File(fileName);
            if (!logFile.exists()) {
                Utils.initExternalDir(false);
                logFile.createNewFile();
            }
            raf = new RandomAccessFile(fileName, "rw");
            raf.seek(raf.length());//將文件記錄指針定位到pos位置。
            raf.writeBytes(sb.toString() + text + "\r\n");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                }
            }
        }
    }
}


最後:在AndroidManifest文件中設置meta data:

   
	//控制是否打印Log
        
   

寫入文件效果 大概如下 有詳細的時間,log等級,內容可以自己控制。

[2014-02-28 16:49:35][E] ### getItemViewType TYPE_ONE_IMAGE 3
[2014-02-28 16:49:35][E] ### position 3
[2014-02-28 16:49:35][E] ### getItemViewType TYPE_ONE_IMAGE 3
[2014-02-28 16:49:35][E] ### getItemViewType TYPE_ONE_IMAGE 3
[2014-02-28 16:49:35][E] ### getItemViewType TYPE_ADS 0
[2014-02-28 16:49:35][E] ### getItemViewType TYPE_ONE_IMAGE 1
[2014-02-28 16:49:35][E] ### getItemViewType TYPE_ONE_IMAGE 2
[2014-02-28 16:49:35][E] ### getItemViewType TYPE_ONE_IMAGE 3
[2014-02-28 16:49:36][I] network state:WIFI
[2014-02-28 16:49:36][I] network state:WIFI
[2014-02-28 16:49:38][I] network state:WIFI

發佈留言