android日志打印工具類

jopen 9年前發布 | 922 次閱讀 Java Android

給大家獻上一款好用的日志打印工具。大家在平時的開發中用的最多的可能就是 Log.i("",""),Log.e("","")...,在要查看的日志比較少的情況下,這種方法用起來確實方便,很容易寫,也很容易查看,然而不知道大家有沒有遇到過這樣一種情況,如果你要查看的數據量非常大,然后用Log類打印出來以后,卻發現只顯示了一部分數據,大部分數據被截斷了。
是的,log打印出來的日志長度是有限的,我之前由于要分析一段從服務器獲取的數據,數據量比較大,用log類打印之后只能看到一部分數據,大部分數據都 被截斷了,后來就自己寫了一個日志打印工具類,把日志打印到手機SD卡上,這樣就能看到完整的數據,該工具我已封裝好,分享給大家。

public class LogTools {

public static void dailyLog(String title, String log) {
    try {
        // 如果外部存儲卡存在且可讀寫
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Date date = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss:SSS");
            String path = Environment.getExternalStorageDirectory()
                    .getAbsolutePath()
                    + File.separator
                    + "mylog"
                    + File.separator
                    + "debuglog["
                    + df.format(date)
                    + "]"
                    + ".txt";
            File file = new File(path);
            // 如果文件不存在,則重新創建
            if (!file.exists()) {
                // 最后一級是文件,前面是路徑,如果路徑不存在則創建路徑
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                // 創建日志文件
                file.createNewFile();
            }
            //寫日志
            FileWriter fw = new FileWriter(file, true);
            fw.flush();
            fw.write("\n[" + df.format(date) +"--"+ tf.format(date) + "]\n");
            fw.write(title + ": " + log);
            fw.write("\n\n");
            fw.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}</pre>
調用:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LogTools.dailyLog("我的日志", "----33222211111111118838777777777777766666666666444444444");
}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!