码迷,mamicode.com
首页 > 移动开发 > 详细

android 中打 Log 的一些技巧

时间:2016-02-20 17:37:05      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:

在 android 平台上搞开发工作,会经常用到一些 Log 输出调试信息。

 

众所周知,android 中有五种类型的 Log , v, d, i, w, e 这里就不再赘 述 (如果对这些不了解的朋友,推荐看 android_Tutor 的博文http://blog.csdn.net/Android_Tutor/article/details/5081713 , 上面讲的很详细)

本文主要讲一下如何统一控制 Log 的输出和关闭。

一般我们会在 debug 的版本中输出 log,而在 release 版本的产品中关闭 log 的输出。这一点是如何做到的呢,下面来看代码。

在你当前工作的工程中建一个新的类文件 Log.java 。这个类文件放在当前工作的包中,(也可以单独建一个包来放这个类文件)

在下面的类文件中,我们把 android中原始的10个 log 函数重新包了一层。定义了一个常量 DEBUG ,当 DEBUG 为 true 时才输出 Log 信息

 1 package com.android.gallery3d.util;  
 2   
 3 public class Log {  
 4     private static final boolean DEBUG = true;  
 5       
 6     public static void v(String tag, String msg) {  
 7         if(DEBUG) {  
 8             android.util.Log.v(tag, msg);  
 9         }  
10     }  
11     public static void v(String tag, String msg, Throwable tr) {  
12         if(DEBUG) {  
13             android.util.Log.v(tag, msg, tr);  
14         }  
15     }  
16     public static void d(String tag, String msg) {  
17         if(DEBUG) {  
18             android.util.Log.d(tag, msg);  
19         }  
20     }  
21     public static void d(String tag, String msg, Throwable tr) {  
22         if(DEBUG) {  
23             android.util.Log.d(tag, msg, tr);  
24         }  
25     }  
26     public static void i(String tag, String msg) {  
27         if(DEBUG) {  
28             android.util.Log.i(tag, msg);  
29         }  
30     }  
31     public static void i(String tag, String msg, Throwable tr) {  
32         if(DEBUG) {  
33             android.util.Log.i(tag, msg, tr);  
34         }  
35     }  
36     public static void w(String tag, String msg) {  
37         if(DEBUG) {  
38             android.util.Log.w(tag, msg);  
39         }  
40     }  
41     public static void w(String tag, String msg, Throwable tr) {  
42         if(DEBUG) {  
43             android.util.Log.w(tag, msg, tr);  
44         }  
45     }  
46     public static void w(String tag, Throwable tr) {  
47         if(DEBUG) {  
48             android.util.Log.w(tag, tr);  
49         }  
50     }  
51     public static void e(String tag, String msg) {  
52         if(DEBUG) {  
53             android.util.Log.e(tag, msg);  
54         }  
55     }  
56     public static void e(String tag, String msg, Throwable tr) {  
57         if(DEBUG) {  
58             android.util.Log.e(tag, msg, tr);  
59         }  
60     }  
61 }  

而当前的包中可以使用 Log.v, Log.i,  Log.w, Log.e, Log.d 来打 Log。

在其它的包中要打Log 也很简单,只要import 該类名就可以了。以上面的类文件为例,只要在其它包的类文件中 import com.android.gallery3d.util.Log; 

就可以使用原来的 Log 函数来打 Log 了。

 

在Release 版本的软件上将 DEBUG 置为 false 即可关闭 Log 输出了。

 

android 中打 Log 的一些技巧

标签:

原文地址:http://www.cnblogs.com/zl1991/p/5203587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!