android 中打 Log 的一些技巧
在 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 输出了。
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了