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:

   <application
        android:name="XXXApplication"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
	//控制是否打印Log
        <meta-data
            android:name="debug"
            android:value="true" />
   </application>


写入文件效果 大概如下 有详细的时间,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

Android应用如何巧妙合理的控制Log,布布扣,bubuko.com

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

上一篇:Android Manifest文件


下一篇:Server Application Unavailable出现的原因及解决方案集锦